从JavaScript中的对象数组创建嵌套对象

Job*_*med 0 javascript arrays json object ecmascript-6

我有对象数据数组:

[
  {"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"}
]
Run Code Online (Sandbox Code Playgroud)

我需要像这样的数据做一个对象:

{
  "Amazon": {
    "UK": {"Arya": null}, 
    "USA": {"Tyrion": null, "Daenarys": null}
  },
  "Google": {
    "KSA": {"Cersi": null, "Dothrokhi": null},
    "USA": {"John": null}
  }
}
Run Code Online (Sandbox Code Playgroud)

任何建议或代码示例都将非常有帮助。我正在尝试,但无法获得正确的结果。

Edd*_*die 10

您可以使用reduce循环遍历数组并将其汇总为一个对象。

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);
Run Code Online (Sandbox Code Playgroud)


Jac*_*ord 5

Use reduce:

const 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"}];
const res = data.reduce((acc, { company, country, employee }) => {
  acc[company] = acc[company] || {};
  acc[company][country] = acc[company][country] || {};
  acc[company][country][employee] = null;
  return acc;
}, {});
console.log(res);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: auto; }
Run Code Online (Sandbox Code Playgroud)