Node JS比较2个嵌套数组数据

绝不

我非常new与block_id进行Node JS比较following arrays如果arrayBblock_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,
          }

        ]
      }
      
    ],
  }
]; 
奥卡·库尔卡尼(Omkar kulkarni)

此函数是递归函数,因此您也可以遍历子级。

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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章