Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Nodo JS Compare 2 datos de matriz anidados

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, } ] } ], } ];
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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 }]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!