솔루션을 작성할 수 있었지만 더 우아하고 효율적인 방법이 있는지 궁금합니다.json의 항목 결합하기
var arr = [];
//I have a array like this:
arr = [{
teacherid: 10,
teacherName: 'andy',
age: 30,
studentid: 1,
studentName: 'A',
studentAge: 10
},
{
teacherid: 10,
teacherName: 'andy',
age: 30,
studentid: 2,
studentName: 'B',
studentAge: 11
}, {
teacherid: 10,
teacherName: 'andy',
age: 30,
studentid: 3,
studentName: 'C',
studentAge: 12
},
{
teacherid: 11,
teacherName: 'May',
age: 40,
studentid: 4,
studentName: 'D',
studentAge: 9
}, {
teacherid: 11,
teacherName: 'May',
age: 40,
studentid: 5,
studentName: 'E',
studentAge: 12
}
];
//want to group the students info in each indiviual teacher like this:
//*
[{
"teacherid": 10,
"teacherName": "andy",
"age": 30,
"studentArr": [{
"studentid": 1,
"studentName": "A",
"studentAge": 10
}, {
"studentid": 2,
"studentName": "B",
"studentAge": 11
}, {
"studentid": 3,
"studentName": "C",
"studentAge": 12
}]
}, {
"teacherid": 11,
"teacherName": "May",
"age": 40,
"studentArr": [{
"studentid": 4,
"studentName": "D",
"studentAge": 9
}, {
"studentid": 5,
"studentName": "E",
"studentAge": 12
}]
}
}]
*//
//my solution
var result = [];
var first = true;
arr = _.sortBy(arr, 'teacherid');
(function() {
for (var i = 0; i < arr.length; i++) {
for (var j = i; j < arr.length; j++) {
console.log("comparing i:" + i + " with j:" + j);
if (i === j && j === arr.length) {
console.log("exit " + i + " : " + j)
return;
} else if (arr[i].teacherid === arr[j].teacherid) {
if (first) {
result.push({
teacherid: arr[j].teacherid,
teacherName: arr[j].teacherName,
age: arr[j].age,
studentArr: [{
studentid: arr[j].studentid,
studentName: arr[j].studentName,
studentAge: arr[j].studentAge
}]
})
} else {
//find in result arr, the obj that contain this teacher and push the student in the array
var teacher = _.find(result, function(item) {
return (item.teacherid === arr[j].teacherid)
})
teacher.studentArr.push({
studentid: arr[j].studentid,
studentName: arr[j].studentName,
studentAge: arr[j].studentAge
})
}
first = false;
} else {
first = true;
i = j - 1;
j = arr.length; //end inner loop, go back to outer loop and check next teacherID
}
}
}
})()
console.log(JSON.stringify(result));
다른 프로그래머가 읽는다면 이것은 두통이 될 것입니다. 이보다 더 나은 솔루션 (더 효율적이고 읽기 쉬운)이 있는지 궁금합니다. 내가 같은 느낌이
무슨 코드를 사용 했 ? 우리가 뭘했는지 모르겠다면 제안을하기가 힘듭니다. –
무엇 ?? 코드는 내 게시물에 있습니다. 전체 솔루션 – user308553