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

156
Visualizações
Merge 2 arrays of object based on specific object key

I have 2 arrays which is contains same id with different value (inside selected) My goal is to merge both become 1 array.

When I use spread operator like this:

data = [
  ...data.filter(
    (a) => a.id === newData.id
  ),
  newData];

It comes the data being override

First array

[
 {
    id: "A527CFFE",
    selected: [
      {
        itemId: "A1",
        text: "Selected 1"
      }
    ]
 }
]

Second array

[
 {
    id: "A527CFFE",
    selected: [
      {
        itemId: "A2",
        text: "Selected 2"
      }
    ]
 }
]

How can I make both of arrays become 1 ? the expected result:

[
 {
    id: "A527CFFE",
    selected: [
      {
        itemId: "A1",
        text: "Selected 1"
      },
      {
        itemId: "A2",
        text: "Selected 1"
      }
    ]
 }
]

What am I doing wrong in the above?

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

You can use Array.reduce() to combine the two arrays into one.

We start by concatenating and then grouping by id. For each item with the same ids we combine the selected arrays.

const arr1 = [ { id: "A527CFFE", selected: [ { itemId: "A1", text: "Selected 1" } ] } ]
const arr2 = [ { id: "A527CFFE", selected: [ { itemId: "A2", text: "Selected 2" } ] } ]

const result = Object.values([...arr1, ...arr2].reduce((acc, { id, selected }) => { 
    acc[id] = acc[id] || { id, selected: [] };
    acc[id].selected = [...acc[id].selected, ...selected];
    return acc;
}, {}));

console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Santiago Gelvez Relatório

0

const arrA=[{id:"A527CFFE",selected:[{itemId:"A1",text:"Selected 1"}]}]
const arrB=[{id:"A527CFFE",selected:[{itemId:"A2",text:"Selected 2"}]}]

const res = arrA.map(e => { // map all items of first array
  const found = arrB.find(x => x.id === e.id) // find item in second array with same id
  return found // check if item has been found in second array
      ? {id: e.id, selected: [...e.selected, ...found.selected]} // if yes, merged selected 
      : e // if no, return only item from first array         
})

console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */

about 4 years ago · Santiago Gelvez 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