The first array is as follows:
var arr = [
{
key: 1,
title: 'aa',
children: [
{
key: 2,
title: 'bb',
children: [
{
key: 3,
title: 'cc',
children: [
{
key: 5,
title: 'ee',
children: [
{
key: 6,
title: 'ff'
},
{
key: 7,
title: 'gg'
},
{
key: 8,
title: 'hh'
}
]
}
]
},
{
key: 4,
title: 'dd',
}
]
}
]
}
]
console.log(arr)
If the second array is as follows:
arr2 = [1, 2, 3, 4, 8]
Then I expect array 3 to be as follows:
arr3 = [4, 8]
答案 0 :(得分:1)
您可以先获取路径,然后过滤给定的键(如果它大于两个路径),然后过滤出该值。
function filter(source, targets) {
function getPath(array, target) {
return array.reduce((r, { key, children }) => {
var temp;
if (key === target) return r.concat(key);
if (children) {
temp = getPath(children, target);
if (temp.length) return r.concat(key, temp);
}
return r;
}, [])
}
var temp = targets.map(k => getPath(source, k));
return targets.filter(v => !temp.some((c => a => a.includes(v) && ++c)(-1)));
}
var array = [{ key: 1, title: 'aa', children: [{ key: 2, title: 'bb', children: [{ key: 3, title: 'cc', children: [{ key: 5, title: 'ee', children: [{ key: 6, title: 'ff' }, { key: 7, title: 'gg' }, { key: 8, title: 'hh' }] }] }, { key: 4, title: 'dd', }] }] }],
result = filter(array, [1, 2, 3, 4, 8]);
console.log(result);