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}
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With