我希望找到优雅的解决方案来过滤嵌套的json数据结构,以便可以应用过滤器功能。
pre-condtions:
recursive.
Y和Z选择过滤器,那么Y和Z的结果应该显示在树结构中。但是,下面显示的kind属性筛选器示例和应用筛选的值是Y .。
谢谢!!
e.g
var dataToFilter = {
"children": [{
"tagPath": "/../../tagPath-1",
"children": [{
"tagPath": "/../../tagPath-1-1",
"children": [{
"tagPath": "/../../tagPath-1-2",
"kind": "Y",
"children": [{
"tagPath": "/../../tagPath-1-3.1",
"kind": "X",
"children": []
},
{
"tagPath": "/../../tagPath-1.3.2",
"kind": "X",
"children": [{
"tagPath": "/../../tagPath-1.3",
"kind": "Y",
"children": []
}]
}
]
},
{
"kind": "Y",
"children": []
}
],
"kind": "X",
}],
"kind": "Y",
}]当值为Y时,对Y属性的期望输出:
var desiredOutput = {
"children": [{
"tagPath": "/../../tagPath-1",
"children": [{
"tagPath": "/../../tagPath-1-2",
"kind": "Y",
"children": [{
"tagPath": "/../../tagPath-1.3",
"kind": "Y",
"children": []
}]
},
{
"kind": "Y",
"children": []
}
],
"kind": "Y",
}]
```发布于 2020-04-17 07:50:56
您可以使用以下函数:
const restructure = (nodes, filter) => nodes.reduce(
(acc, node) => {
const children = restructure(node.children, filter);
return acc.concat(
filter(node)
? {...node, children}
: children
);
},
[]
);它接受filter作为函数。这使您可以决定如何过滤,例如:
const yOnly = restructure(dataToFilter, node => 'Y' === node.kind);或者:
const yAndX = restructure(dataToFilter, node => ['Y', 'X'].includes(node.kind));上面代码的唯一不同之处在于,dataToFilter必须已经是一个节点数组(请参阅下面的完整代码片段)。
const restructure = (nodes, filter) => nodes.reduce(
(acc, node) => {
const children = restructure(node.children, filter);
return acc.concat(
filter(node)
? {...node, children}
: children
);
},
[]
);
const dataToFilter = [{
'tagPath': '/../../tagPath-1',
'children': [{
'tagPath': '/../../tagPath-1-1',
'children': [{
'tagPath': '/../../tagPath-1-2',
'kind': 'Y',
'children': [{
'tagPath': '/../../tagPath-1-3.1',
'kind': 'X',
'children': []
}, {
'tagPath': '/../../tagPath-1.3.2',
'kind': 'X',
'children': [{
'tagPath': '/../../tagPath-1.3',
'kind': 'Y',
'children': []
}]
}]
}, {
'kind': 'Y',
'children': []
}],
'kind': 'X',
}],
'kind': 'Y',
}];
const yOnly = restructure(dataToFilter, node => 'Y' === node.kind);
const xOnly = restructure(dataToFilter, node => 'X' === node.kind);
const yAndX = restructure(dataToFilter, node => ['Y', 'X'].includes(node.kind));
console.log(yOnly);
console.log(xOnly);
console.log(yAndX);
https://stackoverflow.com/questions/61224909
复制相似问题