[英]Node JS Compare 2 nested array data
I am very new
to Node JS
comparing following arrays
with block_id.我对
Node JS
很new
,比较following arrays
和 block_id。 If arrayB
block_id matched with arrayA
block_id adding new attribute isExist:true else false如果
arrayB
block_id 与arrayA
block_id 匹配,则添加新属性 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",
}
]
}
],
}
]
Tried following code to compare尝试以下代码进行比较
const result = arrayA.map(itemA => {
return arrayB
.filter(itemB => itemB.block_id === itemA.block_id)
.reduce((combo, item) => ({...combo, ...item}), {isExist: true})
});
I am getting following我越来越关注
Output Output
[ { isExist: true, block_id: 1 } ]
Expected预期的
[
{
"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,
}
]
}
],
}
];
This function is a recursive function so that you can loop through the children as well.这个 function 是一个递归 function ,因此您也可以遍历子代。
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];
}, [])
}
Now, you can call the function like this现在,您可以像这样调用 function
const result = procesArray(arrayA, arrayB);
result
will be as follows 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
}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.