ret*_*327 0 javascript arrays object node.js
假设我有一个下面的数组:
[
{ 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' },
]
Run Code Online (Sandbox Code Playgroud)
如何将上面的数组转换为对象,如下所示:
{
senior: {
America: 'school-A',
England: 'school-B'
},
junior: {
German: 'school-C',
Italy: 'school-D'
}
}
Run Code Online (Sandbox Code Playgroud)
完成此任务的语法上最简洁的方法是什么?
谢谢你的帮助!!
一种方法是将对象数组减少为单个对象。对于每次迭代,您可以累积对象(最初作为空对象开始{}),以包含当前type键以及国家/地区和学校名称的新键值对。通过使用扩展语法...,您可以将键处先前看到的对象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);Run Code Online (Sandbox Code Playgroud)
每次迭代传播对象可能被视为效率低下,因此您可以改为累积单个对象引用(此时,可能值得考虑使用标准循环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);Run Code Online (Sandbox Code Playgroud)