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

109
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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