gpt4 book ai didi

javascript - 对多维数组应用过滤器并返回过滤后的数据以及父级

转载 作者:行者123 更新时间:2023-12-01 01:18:10 25 4
gpt4 key购买 nike

我有代码片段中提供的多维数组,我想用最里面数组的值过滤该数组,然后与父数组一起返回该值。例如

来自

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);

最佳答案

首先,map总的来说parent并过滤掉不匹配的子项,然后根据 children 过滤中间结果尺寸。

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";
const result = nodes.map(node => ({ ...node,
children: node.children.filter(child => child.value === key)
})).filter(node => node.children.length);
console.log(result);

希望这会有所帮助!

关于javascript - 对多维数组应用过滤器并返回过滤后的数据以及父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54527224/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com