我正在尝试将 对象数组转换为不同的格式
,并参考了此网址。
按多个属性对js对象进行分组
但无法解决问题。
我有一个输入 对象数组
,其中包含班级和章节,我需要根据班级和章节以不同的格式转换或筛选学生。
这是我的代码 https://jsbin.com/nidudisuza/edit?js,output
let expectedout = [
{
class: 1,
sections: [{
"section": "B",
students: [ {
"name": "Test",
"class": 1,
"gender": "M",
"section": "B",
"rollNumber": "123111",
"sports": [
"Badminton",
"Chess"
],
"age": 7
}]
}]
},
{
class: 3,
sections: [{
"section": "B",
students: [{
"name": "Rahul",
"class": 3,
"gender": "M",
"section": "B",
"rollNumber": "1231",
"sports": [
"Badminton",
"Chess"
],
"age": 7
}]
}]
},
{
class: 5,
sections: [{
"section": "C",
students: [
{
"name": "Rajat",
"class": 5,
"gender": "M",
"section": "C",
"rollNumber": "123122",
"sports": [
"Chess"
],
"age": 9
}
]
}]
}
]
const input = [{
"name": "Rahul",
"class": 3,
"gender": "M",
"section": "B",
"rollNumber": "1231",
"sports": [
"Badminton",
"Chess"
],
"age": 7
},
{
"name": "Rajat",
"class": 5,
"gender": "M",
"section": "C",
"rollNumber": "123122",
"sports": [
"Chess"
],
"age": 9
},
{
"name": "Test",
"class": 1,
"gender": "M",
"section": "B",
"rollNumber": "123111",
"sports": [
"Badminton",
"Chess"
],
"age": 7
},
]
function abc() {
// let output =
// data.map((i) => {
// let obj = {};
// obj.class = i.class;
// obj.sections = [];
// obj.sections.push({
// section:obj.section,
// students:[obj]
// })
// return obj;
// })
let output =input.reduce((acc,i)=>{
let cls = i.class;
const found = acc.some(el => el.class === cls);
let obj = {
section:i.section,
students:[]
}
found.sections.students.push[i]
},[])
return output
}
console.log(abc())
}
question
中提到了预期输出..expectedout
- user5711656