Home > Blockchain >  How to add list in the object under the corresponding keys instead of replacing the content?
How to add list in the object under the corresponding keys instead of replacing the content?

Time:11-19

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.

CodePudding user response:

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; }
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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 employee of employees) {
    const company = group[employee.company] ??= {};
    const employeeList = company[employee.position] ??= [];
    const { age, name } = employee;
    employeeList.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));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related