Javascript按对象属性分组

时间:2015-10-05 23:43:38

标签: javascript arrays javascript-objects

我在

下面有一系列对象
var inventory = [
    { Name: "KIT001", SerialNo: "K111", Status: "Out For Cleaning", NewStatus: "Cleaned" },
    { Name: "KIT001", SerialNo: "K112", Status: "Out For Cleaning", NewStatus: "Cleaned" },
    { Name: "KIT001", SerialNo: "K113", Status: "Out For Cleaning", NewStatus: "Cleaned" },
    { Name: "KIT001", SerialNo: "K132", Status: "Out For Cleaning", NewStatus: "Need Cleaning" },
    { Name: "KIT001", SerialNo: "K134", Status: "Out For Cleaning", NewStatus: "Need Cleaning" },
];

我想通过“Out For Cleaning”和“Cleaned”进行分组,以便最终结果返回多个数组,如下所示:

var arr1 = [
    { Name: "KIT001", SerialNo: "K111", Status: "Out For Cleaning", NewStatus: "Cleaned" },
    { Name: "KIT001", SerialNo: "K112", Status: "Out For Cleaning", NewStatus: "Cleaned" },
    { Name: "KIT001", SerialNo: "K113", Status: "Out For Cleaning", NewStatus: "Cleaned" },
];

var arr2 = [
    { Name: "KIT001", SerialNo: "K132", Status: "Out For Cleaning", NewStatus: "Need Cleaning" },
    { Name: "KIT001", SerialNo: "K134", Status: "Out For Cleaning", NewStatus: "Need Cleaning" },
];

更新

我需要先通过STATUS进行一组,然后再进行NEW_STATUS。请注意,这些数组将是动态的。

var STATUS = ["Out For Cleaning", "Out For Repair"];
var NEW_STATUS = ["Cleaned", "Repaired"];

这是我想出来的,它只是由STATUS属性分组。

for (var i = 0; i < STATUS.length; i++) {
          var arr1 = inventory.filter(function (el) {
               return el.Status == STATUS[i];
          });

          if(arr1.length > 0)
               console.log('Final Array: ', arr1)              
}

3 个答案:

答案 0 :(得分:2)

一种方法是过滤数组:

var arr1 = status.filter(function(el) {
    return el.NewStatus == "Cleaned";
});

var arr2 = status.filter(function(el) {
    return el.NewStatus == "Need Cleaning";
});

答案 1 :(得分:0)

这就是我要做的事情:

function GroupBy(array){
  var fields = Array.prototype.slice.call(arguments, 1);
  var field = fields.shift();

  if(field){

    var groupedArray = [];
    for(var i in array){
      var index = array[i][field];
      groupedArray[index] = groupedArray[index] || [];
      groupedArray[index].push(array[i]);
    }

    for(var i in groupedArray)
      groupedArray[i] = GroupBy.bind(null, groupedArray[i]).apply(null, fields);

    return groupedArray;
  }

  return array;
}

然后像这样使用它。按字段对记录进行分组:

var groupedArray = GroupBy(yourArray, "STATUS", "NEW_STATUS");

然后按指定字段获取记录:

var list = groupedArray["Out For Cleaning"]["Need Cleaning"];

答案 2 :(得分:0)

for (var i = 0; i < STATUS.length; i++) {

  var arr1 = inventory.filter(function(el) {
      return el.NewStatus == NEW_STATUS[i-1];
      console.log(el.NewStatus);
  });

  document.getElementById("grey").innerHTML =JSON.stringify(arr1);

  var arr2 = inventory.filter(function(el) {
      return el.NewStatus == NEW_STATUS[i];
  });

  document.getElementById("blue").innerHTML =JSON.stringify(arr2);

}