在json中组合项目

时间:2017-04-01 20:39:13

标签: javascript underscore.js

我能够编写一个解决方案,但我想知道是否有一种更优雅,更有效的方法。

    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));

如果另一位程序员阅读它,那将是一件令人头疼的事。我想知道是否有比这更好的解决方案(更高效和/或更可读)。我觉得我粗暴地强迫这个

2 个答案:

答案 0 :(得分:3)

您可以为教师使用带哈希表的闭包。

var array = [{ 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 }],
    grouped = array.reduce(function (hash) {
        return function (r, a) {
            if (!hash[a.teacherid]) {
                hash[a.teacherid] = {
                    teacherid: a.teacherid,
                    teacherName: a.teacherName,
                    studentArr: []
                };
                r.push(hash[a.teacherid]);
            }
            hash[a.teacherid].studentArr.push({
                studentid: a.studentid,
                studentName: a.studentName,
                studentAge: a.studentAge
            });
            return r;
        };
    }(Object.create(null)), []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

function group(data, column) {
  var generatedData = {};
  $.each(data, function(i, dt) {
    var key = dt[column];
    if (!(key in generatedData)) {
      generatedData[key] = [];
    }
    generatedData[key].push(dt);
  });
  return generatedData;
}

var g = group([
 {
        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
      }
], 'teacherid');

document.write(JSON.stringify(g));