简体   繁体   中英

Node JS Compare 2 nested array data

I am very new to Node JS comparing following arrays with block_id. If arrayB block_id matched with arrayA block_id adding new attribute isExist:true else 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

[ { 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 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

const result = procesArray(arrayA, arrayB);

result will be as follows

[{
  "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
}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM