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

104
Visualizações
Iterate an array of objects

I have an array of objects.

myArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]

I want to create a new dictionary from it: newDict = {a:[1,2,3,4],c:[1,2,3,4]}

I'm totally new to Javascript and Node.js Any kind of help is highly appreciated. Thanks in advance.

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

0

You basically want to group something. For grouping you can usually use .reduce()

On every iteration you iterate over your object entries with Object.entries() and then you always check if your previous value already has that key, if yes, you push it, if not, you create a new array and put your value inside of it.

let myArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]


let result = myArray.reduce((prev, curr) => {
   Object.entries(curr).forEach(([key, value]) => {
      if(prev[key]) {
         prev[key].push(value)
      } else {
         prev[key] = [value]
      }
   })
   return prev;
}, {})


console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

Alternatively you can also do it in a for loop, in case you are unfamiliar with the reduce method.

const myArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]

const wantedProperties = ['a', 'b', 'd']

const mydict = {}
for (const item of myArray) {
  for (const [key, value] of Object.entries(item)) {
    if (wantedProperties.includes(key)) {
     mydict[key] = (mydict[key] || []).concat(value)
    }
  }
}

console.log(mydict)

about 4 years ago · Juan Pablo Isaza Relatório

0

let targetArray = [{a:1,b:1,c:1,d:1},{a:2,b:2,c:2,d:2},{a:3,b:3,c:3,d:3},{a:4,b:4,c:4,d:4}]


let result = targetArray.reduce((accc, curr) => {
   Object.entries(curr).forEach(([key, value]) => {
      if(!accc[key]) {
         accc[key] = [value]
      } else {
         accc[key].push(value)
      }
   })
   return accc;
}, {})


console.log(result);
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