Reputation: 47
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,
}
]
}
],
}
];
Upvotes: 2
Views: 69
Reputation: 1215
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
}]
Upvotes: 1