Soy muy new en Node JS comparando las following arrays con block_id. Si arrayB block_id coincide con arrayA block_id agregando un nuevo atributo 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", } ] } ], } ]Probé el siguiente código para comparar
const result = arrayA.map(itemA => { return arrayB .filter(itemB => itemB.block_id === itemA.block_id) .reduce((combo, item) => ({...combo, ...item}), {isExist: true}) });estoy siguiendo
Producción
[ { isExist: true, block_id: 1 } ]
Esperado
[ { "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, } ] } ], } ];Esta función es una función recursiva, por lo que también puede recorrer los elementos secundarios.
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]; }, []) }Ahora, puedes llamar a la función así
const result = procesArray(arrayA, arrayB); el result sera el siguiente
[{ "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 }]