Javascript 节点JS比较2个嵌套数组数据
我非常喜欢Javascript 节点JS比较2个嵌套数组数据,javascript,node.js,Javascript,Node.js,我非常喜欢new到Node JS比较以下数组与block\u id。如果arrayBblock\u id与arrayAblock\u id匹配,则添加新属性isExist:true否则false var arrayB = [{ "block_id": 1 },{ "block_id": 3 }]; const arrayA = [ { "block_id": 1, "block_name": &q
new
到Node JS
比较以下数组
与block\u id。如果arrayB
block\u id与arrayA
block\u 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",
}
]
}
],
}
]
尝试使用以下代码进行比较
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\u 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);
结果将如下所示
[{
"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
}]