将对象数组过滤为对象

时间:2015-12-04 18:10:38

标签: javascript arrays object

如何将以下输入转换为输出。

输入:

[{"id":1, "subid":5}, 
{"id":1, "subid":9}, 
{"id":2, "subid":16}, 
{"id":2, "subid":27}]

输出:

[{1:[5,9]},
{2:[16,27]}]

这是我到目前为止所尝试的:

var newobj = new Object(); 
listOfObject.forEach(function(i) { 
   var id = i.id 
   newobj[id] = [] 
   newobj[id].push(i.subid) 
   return newobj 
})

4 个答案:

答案 0 :(得分:5)

减少这样的数据:

var arrayData = [{"id":1, "subid":5}, {"id":1, "subid":9}, {"id":2, "subid":16}, {"id":2, "subid":27}];

var result = arrayData.reduce(function (result, obj) {
  var id = obj.id;
  result[id] = (result[id] || []);
  result[id].push(obj.subid);
  return result;
}, {});

答案 1 :(得分:3)

Underscore实用程序对于数组和对象操作非常方便。试试这个:

counter

答案 2 :(得分:0)

var input = [
    {"id":1, "subid":5}, 
    {"id":1, "subid":9}, 
    {"id":2, "subid":16}, 
    {"id":2, "subid":27}
];

var output = [];
for (var i = 0; i < input.length; i++) {
  var id = input[i].id;
  var subid = input[i].subid;
  if (output[id] == null) {
    output[id] = [];
  }
  output[id].push(subid);
}

答案 3 :(得分:0)

我只是遍历输入数组并检查是否存在现有属性,然后添加新对象或推送到现有数组。

&#13;
&#13;
var input = [
  {"id":1, "subid":5}, 
  {"id":1, "subid":9}, 
  {"id":2, "subid":16}, 
  {"id":2, "subid":27}
];

var output = [];

input.forEach(function(a){
  var existing = output.find(function(b){
      return b.hasOwnProperty(a.id);
    });
  existing
    ? existing[a.id].push(a.subid)
    : output.push({[a.id]: [a.subid]});
});

console.log(output);
&#13;
&#13;
&#13;