通过基于javascript中每个对象的属性值对对象数组进行分组来创建新的对象数组

时间:2015-08-02 04:45:54

标签: javascript arrays object

我有一个像下面这样的对象数组,我想通过基于java脚本中每个对象的属性值对java脚本对象数组进行分组来创建新的对象数组

这里我想基于组ID对对象进行分组,并将其存储到具有唯一组ID的对象数组中。

这是我的目标:

var Object = [
 {"Name":15,"GroupID":1,"ComplexObject":1}`object1`    
 {"Name":16,"GroupID":1,"ComplexObject":1}`object2`   
 {"Name":17,"GroupID":2,"ComplexObject":2}`object3
 {"Name":18,"GroupID":2,"ComplexObject":2}`object4`
 {"Name":15,"GroupID":3,"ComplexObject":3}`object5`
 {"Name":16,"GroupID":3,"ComplexObject":3}`object6`
 {"Name":17,"GroupID":4,"ComplexObject":4}`object7`
 {"Name":18,"GroupID":4,"ComplexObject":4}`object8` ];

2 个答案:

答案 0 :(得分:0)

var new_arr = [];

Objects.forEach(function(object) {
  if (new_arr.length <= object.GroupID) {
    new_arr[object.GroupID] = [];
  }
  new_arr[object.GroupID].push(object);
});

更新:如果你想要数组的长度,只需使用:

var new_arr = [];

Objects.forEach(function(object) {
  if (new_arr.length < object.GroupID) {
    new_arr[object.GroupID - 1] = [];
  }
  new_arr[object.GroupID - 1].push(object);
});

你会得到这个:

result

答案 1 :(得分:0)

您可以通过检查组ID并将其推送到数组对象来尝试这种方式。

  var data = [ 
                {"Name":15,"GroupID":1,"ComplexObject":1},
                {"Name":16,"GroupID":1,"ComplexObject":1},
                {"Name":17,"GroupID":2,"ComplexObject":2},
                {"Name":18,"GroupID":2,"ComplexObject":2},
                {"Name":15,"GroupID":3,"ComplexObject":3},
                {"Name":16,"GroupID":3,"ComplexObject":3},
                {"Name":17,"GroupID":4,"ComplexObject":4},
                {"Name":18,"GroupID":4,"ComplexObject":4}
             ];

  console.log("Original Data : ", data);

  var previousGroupId;
  var newObject = new Object();
  for(index in data){
      var groupId = data[index].GroupID;
      if(groupId != previousGroupId){
          var newGroup = "GroupId" + groupId;
          newObject[newGroup] = new Array();
          for(index in data){
              if(data[index].GroupID == groupId){
                  var customObject = {
                      "GroupID" : groupId,
                      "Name" : data[index].Name,
                      "ComplexObject" : data[index].ComplexObject
                  };
                  newObject[newGroup].push(customObject);        
              }
          }
      }
      previousGroupId = groupId;
  }

  console.log("Grouped data : ", newObject);

jsFiddle