簡體   English   中英

Node JS比較2個嵌套數組數據

[英]Node JS Compare 2 nested array data

我對Node JSnew ,比較following arrays和 block_id。 如果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",
          }

        ]
      }
      
    ],
  }
]

嘗試以下代碼進行比較

const result = arrayA.map(itemA => {
    return arrayB
        .filter(itemB => itemB.block_id === itemA.block_id)
        .reduce((combo, item) => ({...combo, ...item}), {isExist: true})
});

我越來越關注

Output

[ { 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 是一個遞歸 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];
  }, [])
}

現在,您可以像這樣調用 function

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
}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM