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

110
Vistas
How to add list in the object under the corresponding keys instead of replacing the content?

I came from PHP and can not perform in JS simple task of associative arrays can be done in PHP. Maybe I am using approach which does not fit with this language.

So, I have an object which I have to rebuild for further needs. The info is getting added in while cycle.

Lets say I have the following:

array[0] = { company: 'kfc', position: 'chicken', name: 'Andrejs', age: '20 days' }

array[1] = { company: 'kfc', position: 'chicken', name: 'Alex', age: '15 days' }

array[2] = { company: 'mcdonalds', position: 'chicken', name: 'Lena', age: '23 days' }

I whish to get the info in the following:

{
 {kfc: 
  {chicken: 
   {name: "Alex", Age: "15 days"}, 
   {name: "Andrejs", Age: "20 days"}
  }
 }, 
 {mcdonalds: 
  { chicken: 
   {name: "Lena", age: 23 days}
  }
 }
}

I have tried:

  1. Create an object: food = {};
  2. to create object like this (in while cycle):
food = {array[i].company : {array[i].position : {name: array[i].name, age: array[i].age}}}

This did not work, because it overrates the data which were written in previous while round. 3. Create variable m to give an unique key:

food[m] = {array[i].company : {array[i].position : {name: array[i].name, age: array[i].age}}}
m++;

This did not work, because I had 3 separate strings in object. 4. To use a keys before = sign:

food[array[i].company][array[i].position] = {name: array[i].name, age: array[i].age}

This gives an error, because such keys does not exist during the first round.

I have checked some object tutorials, but did not find resolution. Will very thankful to those, who will point the correct way of creating associative objects in JS.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can get the desired output using Array.reduce(), grouping on company and position.

For each item, we check if there are any existing entries for that key, if not we create them.

Each position property will contain an array of all entries for that position.

    

let arr = [
    { company: 'kfc', position: 'chicken', name: 'Andrejs', age: '20 days' },
    { company: 'kfc', position: 'chicken', name: 'Alex', age: '15 days' },
    { company: 'mcdonalds', position: 'chicken', name: 'Lena', age: '23 days' }
];

const output = arr.reduce((acc, { company, position, age, name }) => { 
    // If no existing items are here, create an empty object for this company.
    acc[company] = acc[company] || { };
    // If no existing items are here, create an empty array for this position. 
    acc[company][position] = acc[company][position] || [];
    // Add the entry for the relevant position
    acc[company][position].push({ age, name})
    return acc;
}, {})

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

about 4 years ago · Juan Pablo Isaza Denunciar

0

Here's a function groupEmployees which will organize the array of employees into a hierarchical object:

TS Playground link

function groupEmployees (employees) {
  const group = {};
  for (const { age, company, name, position } of employees) {
      ((group[company] ??= {})[position] ??= []).push({ age, name });
  }
  return group;
}

const employees = [
  { company: 'kfc', position: 'chicken', name: 'Andrejs', age: '20 days' },
  { company: 'kfc', position: 'chicken', name: 'Alex', age: '15 days' },
  { company: 'mcdonalds', position: 'chicken', name: 'Lena', age: '23 days' },
];

console.log(groupEmployees(employees));

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