[在此处输入图片说明] [1]请帮助我,因为我正在努力争取一些工作。我有一个JSON代表我的应用程序中的树视图。
{
name: 'Global', toggled: true, children: [
{
name: 'Region A', nodeid: 0,chosen: true,pushed: false,
children: [
{ name: 'Town A', nodeid: 1, chosen: true, pushed: false,
children: [{
name : "child 1", pushed: false, chosen:false
}]
},
{ name: 'Town B', nodeid: 2, chosen: false, pushed: false,
children: [{
name : "child 2", pushed: false, chosen: false
}]
}
]
}
]
};
我想要做的是遍历我的JSON,只返回选中属性为true的条目。
到目前为止,我尝试了许多没有成功的事情,你们能帮助我吗?
https://i.stack.imgur.com/r61MO.jpg
onPush(e){
var chosennodes = filters.filterTreeChosen(this.state.data);
this.setState({selectednodes: chosennodes});
}
然后过滤器本身:
[Object.filter = (obj, predicate) =>
Object.keys(obj)
.filter( key => predicate(obj\[key\]) )
.reduce( (res, key) => (res\[key\] = obj\[key\], res), {} );
export const isChosen = (chosen) =>{
return chosen == true;
}
export const filterTreeChosen = (nodes) => {
var filtered = Object.filter(nodes, node => node.chosen == true);
console.log(filtered);
};][1]
答案 0 :(得分:1)
检查一下。我认为它应该适用于你的任务。
const tree = {
name: 'Global', toggled: true, children: [
{
name: 'Region A', nodeid: 0,chosen: true,pushed: false,
children: [
{ name: 'Town A', nodeid: 1, chosen: true, pushed: false,
children: [{
name : "child 1", pushed: false, chosen:false
}]
},
{ name: 'Town B', nodeid: 2, chosen: false, pushed: false,
children: [{
name : "child 2", pushed: false, chosen: false
}]
}
]
}
]
};
function getChosenNodes (nodes) {
let result = [];
nodes.forEach(node => {
if (node.chosen) {
result = result.concat([node.nodeid]);
}
if (node.children) {
result = result.concat(getChosenNodes(node.children));
}
})
return result;
}
console.log(getChosenNodes([tree]))

我只返回了nodeid
,但您可以根据需要进行更改。