Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

212
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda