我非常new
想与block_id进行Node JS
比较following arrays
。如果arrayB
block_id与block_id匹配,arrayA
则添加新属性isExist:true,否则返回false
var arrayB = [{ "block_id": 1 },{ "block_id": 3 }];
const arrayA = [
{
"block_id": 1,
"block_name": "test 1",
"children": [
{
"block_id": 2,
"block_name": "test 2",
"children": [
{
"block_id": 3,
"block_name": "test 2",
}
]
}
],
}
]
尝试以下代码进行比较
const result = arrayA.map(itemA => {
return arrayB
.filter(itemB => itemB.block_id === itemA.block_id)
.reduce((combo, item) => ({...combo, ...item}), {isExist: true})
});
我正在关注
输出
[ { isExist: true, block_id: 1 } ]
预期的
[
{
"block_id": 1,
"block_name": "test 1",
"isExist": true,
"children": [
{
"block_id": 2,
"block_name": "test 2",
"isExist": false,
"children": [
{
"block_id": 3,
"block_name": "test 2",
"isExist": true,
}
]
}
],
}
];
此函数是递归函数,因此您也可以遍历子级。
function procesArray(arr, arrayB) {
return arr.reduce((result, item) => {
const itemInB = arrayB.find(itemB => itemB.block_id == item.block_id)
if (itemInB)
item.isExist = true;
if (item.children)
procesArray(item.children, arrayB);
return [...result, item];
}, [])
}
现在,您可以像这样调用函数
const result = procesArray(arrayA, arrayB);
result
将如下
[{
"block_id": 1,
"block_name": "test 1",
"children": [{
"block_id": 2,
"block_name": "test 2",
"children": [{
"block_id": 3,
"block_name": "test 2",
"isExist": true
}]
}],
"isExist": true
}]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句