3 回答
TA贡献1797条经验 获得超4个赞
let data = [
{
"class": "X",
"student":[
{
"name": "Bumblebee",
"id":"SAB77"
}
]
},
{
"class": "X",
"student":[
{
"name": "Omega",
"id":"SAB78"
}
]
},
{
"class": "IX",
"student":[
{
"name": "Pluto",
"id":"RBC17"
}
]
},
{
"class": "IX",
"student":[
{
"name":"16 psyche",
"id":"RBC18"
}
]
}
];
const output = data.reduce((acc, rec) => {
const obj = acc.find(ele => ele.class === rec.class);
if (obj) {
obj.student = [...obj.student, ...rec.student];
} else {
acc.push(rec);
}
return acc;
}, []);
console.log(output)
TA贡献2011条经验 获得超2个赞
尝试这个。
let data = [
{
"class": "X",
"student": [
{
"name": "Bumblebee",
"id": "SAB77"
}
]
},
{
"class": "X",
"student": [
{
"name": "Omega",
"id": "SAB78"
}
]
},
{
"class": "IX",
"student": [
{
"name": "Pluto",
"id": "RBC17"
}
]
},
{
"class": "IX",
"student": [
{
"name": "16 psyche",
"id": "RBC18"
}
]
}
]
var reOrganized = [];
var unseen_classes = [];
for (var i = 0; i < data.length; i++) {
if (unseen_classes.indexOf(data[i].class) !== -1) {
for (var j = 0; j < reOrganized.length; j++) {
if (reOrganized[j].class === data[i].class) {
reOrganized[j].students.push(data[i].student[0])
}
}
}
else {
unseen_classes.push(data[i].class)
reOrganized.push({
class: data[i].class,
students: [data[i].student[0]]
})
}
}
console.log(reOrganized)
TA贡献1844条经验 获得超8个赞
let data = [{
"class": "X",
"student": [{
"name": "Bumblebee",
"id": "SAB77"
}]
},
{
"class": "X",
"student": [{
"name": "Omega",
"id": "SAB78"
}]
},
{
"class": "IX",
"student": [{
"name": "Pluto",
"id": "RBC17"
}]
},
{
"class": "IX",
"student": [{
"name": "16 psyche",
"id": "RBC18"
}]
}
];
const result = data.reduce((acc, obj) => {
let existedObj = acc.length && acc.find(ele => ele.class === obj.class);
if (!acc.length || !existedObj) {
acc.push(obj);
return acc;
}
existedObj.student = [...existedObj.student, ...obj.student];
return acc;
}, []);
console.log(result);
添加回答
举报