【发布时间】:2019-02-05 03:04:40
【问题描述】:
我有代码 sn-p 上提供的多维数组,我想用最内层数组的值过滤该数组,然后将该值与 parent 一起返回。 例如
来自
const nodes = [
{
value: 'Documents',
label: 'Documents',
children: [
{
value: 'Employee Evaluations.zip',
label: 'Employee Evaluations.zip',
},
{
value: 'Expense Report.pdf',
label: 'Expense Report.pdf',
},
{
value: 'notes.txt',
label: 'notes.txt',
},
],
},
{
value: 'Photos',
label: 'Photos',
children: [
{
value: 'nyan-cat.gif',
label: 'nyan-cat.gif',
},
{
value: 'SpaceX Falcon9 liftoff.jpg',
label: 'SpaceX Falcon9 liftoff.jpg',
},
],
},
];
如果我按“notes.txt”过滤它应该会产生
[
{
value: 'Documents',
label: 'Documents',
children: [
{
value: 'notes.txt',
label: 'notes.txt',
}
]
]
这是我尝试过的,但它只返回最里面的过滤内容
const nodes = [
{
value: 'Documents',
label: 'Documents',
children: [
{
value: 'Employee Evaluations.zip',
label: 'Employee Evaluations.zip',
},
{
value: 'Expense Report.pdf',
label: 'Expense Report.pdf',
},
{
value: 'notes.txt',
label: 'notes.txt',
},
],
},
{
value: 'Photos',
label: 'Photos',
children: [
{
value: 'nyan-cat.gif',
label: 'nyan-cat.gif',
},
{
value: 'SpaceX Falcon9 liftoff.jpg',
label: 'SpaceX Falcon9 liftoff.jpg',
},
],
},
];
let key="notes.txt";
//let filtered=nodes.filter(n=>n.value===key);
let cfiltered=nodes.map(n=>n.children.filter(n1=>n1.value===key));
//console.log(filtered);
console.log(cfiltered);
【问题讨论】:
标签: javascript arrays dictionary filter ecmascript-6