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

174
Visualizações
Creating an array from each key in an array of objects

I have an array that looks similar to this: The array of objects is much larger and each object has more properties, this is the structure though.

  let arr = [
    { id: 1, name: "tony", hatColor: "blue" },
    { id: 2, name: "larry", hatColor: "red" },
    { id: 3, name: "stuart", hatColor: "green" },
  ];

I want to create an array for each key in this array so I have an array with all ids, an array with all names, and one with all hatColors.

idArr = [1, 2, 3];
nameArr = [tony, larry, stuart];
hatColorArr = [blue, red, green];

I won't know exactly what the array of objects looks like as it is returned from another script.

What I have tried is:

  for (var [key, value] of Object.entries(arr)) {
    for (var [key, value] of Object.entries(value)) {
      var result = arr.map(({ key }) => key);
      console.log(result);
    }
  }

This returns an array of undefined. I hope there is a way to do this, I don't want to write a lot of hard coded if push statements to get this to work.

Thanks.

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

0

You can use Array.map to extract the property values for each item in the array.

let arr=[{id:1,name:"tony",hatColor:"blue"},{id:2,name:"larry",hatColor:"red"},{id:3,name:"stuart",hatColor:"green"}];

function groupPropValues(objs, prop){
    return objs.map(e => e[prop])
}

idArr = groupPropValues(arr, 'id');
nameArr = groupPropValues(arr, 'name');
hatColorArr = groupPropValues(arr, 'hatColor');
console.log(idArr, nameArr, hatColorArr)

If you want to automatically generate the arrays, you can do so by getting the properties of each object in the array, then fetching the values and storing them in an object.

let arr=[{id:1,name:"tony",hatColor:"blue"},{id:2,name:"larry",hatColor:"red"},{id:3,name:"stuart",hatColor:"green"}];

function groupPropValues(objs, prop) {
  return objs.map(e => e[prop])
}

const props = [...new Set(arr.reduce((a,b) => (a.push(Object.keys(b)), a), []).flat())]

const result = props.reduce((a,b) => (a[b] = groupPropValues(arr, b), a), {})

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