2 回答
TA贡献1865条经验 获得超7个赞
每当您看到看起来像您的分组等的数据时,Array.reduce通常都符合要求。
例如。
const data = [
{
time: 2019,
role: 'student',
age: 22
},
{
time: 2019,
role: 'teacher',
age: 37
},
{
time: 2020,
role: 'teacher',
age: 45
}
];
//..should look like:
const desiredData = data.reduce((a, v) => {
a[v.time] = a[v.time] || {student: null, teacher: null};
a[v.time][v.role] = v.age;
return a;
}, {});
console.log(desiredData);
TA贡献1804条经验 获得超3个赞
找到以下问题的解决方案:
console.clear()
const data = [
{
time: 2019,
role: 'student',
age: 22
},
{
time: 2019,
role: 'teacher',
age: 37
},
{
time: 2020,
role: 'teacher',
age: 45
}
]
const m = {}
const len = data.length
for (let i = 0; i < len; ++i) {
if (!m[data[i].time]) m[data[i].time] = {student: null, teacher: null}
if (data[i].role === 'student')
m[data[i].time].student = data[i].age
else if (data[i].role === 'teacher')
m[data[i].time].teacher = data[i].age
}
console.log(m)
添加回答
举报