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

210
Visualizações
I want to create an object with the key as a property from the object and value as an array of objects matching the key (javascript)

I have a given object to iterate and create another object in the below format (newObj) Given object:

let obj = [
  {a: 1, b: 232},
  {a: 1, b: 2},
  {a: 1, b: 256},
  {a: 2, b: 3},
  {a: 2, b: 3343},
  {a: 3, b: 4}
];

Expected object:

newObj = {
    1: [{a: 1, b: 232}, {a: 1, b: 2}, {a: 1, b: 256}],
    2: [{a: 2, b: 3}],
    3: [{a: 3, b: 4}]
}

Code:

let newObj = {};

obj.forEach(element => {
  if (newObj[element.a]) {
    let key = element.a;
    newObj[key] = newObj[key].push(element);
  }
  newObj[element.a] = [element];
});

console.log(newObj);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

We create a result object, loop through every object in obj array, if we don't have the object a key in the result object, we add him (a: []), and after that we push the entire object to result[a] array

let obj = [
  {a: 1, b: 232},
  {a: 1, b: 2},
  {a: 1, b: 256},
  {a: 2, b: 3},
  {a: 2, b: 3343},
  {a: 3, b: 4}
];

let result = {};

for(const {a, b} of obj) {
  if(!result[a]) result[a] = []
  result[a].push({a, b})
}

console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

To address your updated code snippet, you need to only create a new array for a given key if they key does not exist.

let obj = [
  { a: 1, b:  232 },
  { a: 1, b:    2 },
  { a: 1, b:  256 },
  { a: 2, b:    3 },
  { a: 2, b: 3343 },
  { a: 3, b:    4 }
];

let newObj = {};

obj.forEach(element => {
  let key = element.a;
  if (!newObj[key]) {
    newObj[key] = []; // Only initialize if undefined/null
  }
  newObj[key].push(element); // Always push
});

console.log(newObj);
.as-console-wrapper { top: 0; max-height: 100% !important; }

A more modern approach would be to simply bin them by the a key by reducing and spreading.

const obj = [
  { a: 1, b:  232 },
  { a: 1, b:    2 },
  { a: 1, b:  256 },
  { a: 2, b:    3 },
  { a: 2, b: 3343 },
  { a: 3, b:    4 }
];

const newObj = obj.reduce((acc, o) => ({
  ...acc,
  [o.a]: [...(acc[o.a] ?? []), o]
}), {});

console.log(newObj);
.as-console-wrapper { top: 0; max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use reduce for that

let obj = [
  {a: 1, b: 232},
  {a: 1, b: 2},
  {a: 1, b: 256},
  {a: 2, b: 3},
  {a: 2, b: 3343},
  {a: 3, b: 4}
];


const newObj = obj.reduce((res, {a, b}) => {
  return {
  ...res,
  [a] : [...(res[a] || []), {a, b}]
  }
}, {})

console.log(newObj)

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