-
繁星coding
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)
-
森林海
尝试这个。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)
-
婷婷同学_
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);