【发布时间】:2021-04-13 05:32:48
【问题描述】:
我正在尝试为反应表编写搜索栏过滤器。
困难的部分是JSON数据结构,它可能具有未知深度的父子关系,例如:
data = [
{
input: "row 0 ",
output: "output of the first row"
subRows: [],
},
{
input: "row 1",
output: "output of the second row"
subRows: [
{
input: "third row 1.0",
output: "output of the 3° row"
subRows: [
{
input: "row 1.0.0",
output: "output of the third row"
subRows: [],
},
],
},
{
input: "row 1.1",
output: "output of 2 rows after the third (fifth)"
subRows: []
},
],
},
];
附加信息:上述 JSON 的每个对象在我的 html(jsx) 表中都表示为一行,而他的 subRows 是其他行,可以通过用户单击来展开。
我认为我可以使用 ES6 过滤器功能来处理它,但我不知道如何。
如果用户在搜索栏中输入例如:“third”
,这就是我所期望的结果 {
input: "third row 1.0",
output: "output of the 3° row"
subRows: []
},
{
input: "row 1.1",
output: "output of 2 rows after the third (fifth)",
subRows: []
},
这是我的代码:
const updateFilter = (filterValue) => {
let results = data.filter(function f(row) {
if (Object.values(row).includes(filterValue.toLowerCase())) {
return true;
}
if (row.subRows && row.subRows.length > 0) {
return (row.subRows = row.subRows.filter(f));
}
});
console.log(JSON.stringify(results));
};
}
这里是codePen中的代码:https://codepen.io/ardiz90/pen/yLajjRQ?editors=0012
感谢您的帮助!
编辑:结果我无法展平行,因为表需要树结构中的数据才能呈现它,所以下面编写的展平行的解决方案是不可行的..
【问题讨论】:
标签: javascript reactjs ecmascript-6 filter uisearchbar