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

100
Visualizações
Merging array of object in to a single array of object

I am trying to merge all the items object from a JSON file into a single item object. The JSON file structure looks like this;

[
  {"items":["product1","product2","product3"]},
  {"items":["product4","product5","product6"]},
]

What I want to achieve is to merge all the items into a single items object such as;

[
  {"items":["product1","product2","product3,"product4","product5","product6"]},
]

I have been trying concat, or spreading but couldn't make either work. How can I achieve this or what is the best method to use in this case?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You want reduce, a function whose job it is to "reduce" a list of values to a single value. In JavaScript, reduce is a method on every array. The first parameter to reduce is a function taking the current tally, then the current item, and returns the next tally. The second argument to reduce is the initial value of the tally, in our case an 'items' object with and empty array.

const LIST = [
  {"items":["product1","product2","product3"]},
  {"items":["product4","product5","product6"]},
]

const { items } = LIST.reduce((acc, element) => ({
  items: [...acc.items, ...element.items]
}), { items: [] })

console.log(items)

about 4 years ago · Juan Pablo Isaza Relatório

0

Use Array.reduce() and the spread operator to push the items into a single object and array:

const arr = [
  {"items":["product1","product2","product3"]},
  {"items":["product4","product5","product6"]},
]

const res = arr.reduce((acc, cur) => {
  acc[0].items.push(...cur.items);
  return acc;
}, [{'items': []}]);

console.log(res);

about 4 years ago · Juan Pablo Isaza Relatório

0

There doesn't much point in an array with only one object. Why not create an array and push/spread each object's items value into it with a simple loop. A lot more readable than reduce.

const data = [
  { items: ['product1', 'product2', 'product3'] },
  { items: ['product4', 'product5', 'product6'] }
];

const items = [];

for (const obj of data) {
  items.push(...obj.items);
}

console.log(items);

about 4 years ago · Juan Pablo Isaza 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