2

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

        ]
      }
      
    ],
  }
]; 
0

1 Answer 1

1

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
}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.