假設我在下面有一個陣列:
[
{ type: 'senior', schoolName: 'school-A', country: 'America' },
{ type: 'senior', schoolName: 'school-B', country: 'England' },
{ type: 'junior', schoolName: 'school-C', country: 'German' },
{ type: 'junior', schoolName: 'school-D', country: 'Italy' },
]
如何將上面的陣列轉換為如下所示的物件:
{
senior: {
America: 'school-A',
England: 'school-B'
},
junior: {
German: 'school-C',
Italy: 'school-D'
}
}
實作此目的的語法最簡潔的方法是什么?
謝謝你的幫助!!
uj5u.com熱心網友回復:
一種方法是將物件陣列減少為單個物件。對于每次迭代,您可以累積您的物件(最初作為一個空物件開始{}),以包含當前type鍵以及國家和學校名稱的新鍵值對。通過使用spread 語法,...您可以將之前在type鍵上看到的物件(來自您當前累積的物件)與您正在構建的新物件合并。
請參閱以下示例中的代碼注釋:
const arr = [ { type: 'senior', schoolName: 'school-A', country: 'America' }, { type: 'senior', schoolName: 'school-B', country: 'England' }, { type: 'junior', schoolName: 'school-C', country: 'German' }, { type: 'junior', schoolName: 'school-D', country: 'Italy' }, ];
const res = arr.reduce((acc, {type, schoolName, country}) => ({ // obtain the kys from the current object using destructuring assignment
...acc, // merge the current object stored in acc into the current object `{}` we're building
[type]: { // using "computed property names"
...acc[type], // merge inner object (still worrks when acc[type] === undefined)
[country]: schoolName
}
}), {}); // start with an initial empty object `{}` that we'll accumulate to
console.log(res);
每次迭代傳播您的物件可能會被視為低效,因此您可以改為累積單個物件參考(此時,可能值得考慮使用標準for回圈來代替可讀性):
const arr = [ { type: 'senior', schoolName: 'school-A', country: 'America' }, { type: 'senior', schoolName: 'school-B', country: 'England' }, { type: 'junior', schoolName: 'school-C', country: 'German' }, { type: 'junior', schoolName: 'school-D', country: 'Italy' }, ];
const res = arr.reduce((acc, {type, schoolName, country}) => {
if(!acc[type]) acc[type] = {};
acc[type][country] = schoolName;
return acc;
}, {});
console.log(res);
uj5u.com熱心網友回復:
我認為這是您的問題的一個簡單易讀的解決方案(如果同一個實體的多個實體出現在同country一個type,最后一次出現將覆寫所有以前的出現)
let data = [
{ type: 'senior', schoolName: 'school-A', country: 'America' },
{ type: 'senior', schoolName: 'school-B', country: 'England' },
{ type: 'junior', schoolName: 'school-C', country: 'German' },
{ type: 'junior', schoolName: 'school-D', country: 'Italy' },
];
let res = {};
data.forEach(e => {
if(!res[e.type])
res[e.type] = {};
res[e.type][e.country] = e.schoolName;
});
console.log(res);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361583.html
標籤:javascript 节点.js 数组 目的
下一篇:物件INSIDE陣列的條件渲染
