Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create nested object from array of objects in JavaScript [closed]

I have array of objects data:

[
  {"company": "Google", "country": "USA", "employee": "John"},
  {"company": "Amazon", "country": "UK", "employee": "Arya"},
  {"company": "Google", "country": "KSA", "employee": "Cersi"},
  {"company": "Amazon", "country": "USA", "employee": "Tyrion"},
  {"company": "Amazon", "country": "USA", "employee": "Daenarys"},
  {"company": "Google", "country": "KSA", "employee": "Dothrokhi"}
]

How can I create a nested object like below?

{
  "Amazon": {
    "UK": {"Arya": null}, 
    "USA": {"Tyrion": null, "Daenarys": null}
  },
  "Google": {
    "KSA": {"Cersi": null, "Dothrokhi": null},
    "USA": {"John": null}
  }
}
like image 961
Jobayer Ahmmed Avatar asked May 06 '19 07:05

Jobayer Ahmmed


Video Answer


1 Answers

You can use reduce to loop thru the array and summarize it into an object.

let arr = [{"company":"Google","country":"USA","employee":"John"},{"company":"Amazon","country":"UK","employee":"Arya"},{"company":"Google","country":"KSA","employee":"Cersi"},{"company":"Amazon","country":"USA","employee":"Tyrion"},{"company":"Amazon","country":"USA","employee":"Daenarys"},{"company":"Google","country":"KSA","employee":"Dothrokhi"}]

let result = arr.reduce((c, v) => {
  c[v.company] = c[v.company] || {};                         //Init if company property does not exist
  c[v.company][v.country] = c[v.company][v.country] || {};   //Init if country property does not exist
  c[v.company][v.country][v.employee] = null;                //Add employee property with null value
  return c;
}, {});

console.log(result);
like image 172
Eddie Avatar answered Sep 30 '22 13:09

Eddie