Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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,
          }

        ]
      }
      
    ],
  }
]; 
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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
}]
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda