Javascript:按ID分组对象数组

时间:2016-11-11 19:45:19

标签: javascript

我有一个问题,我似乎几乎没有任何线索可以得到答案。

我不知道我做错了什么。

代码:

function groupBy(arr, cb) {
  var groups = {};
  arr.forEach(function(o) {
    var group = JSON.stringify(cb(o));
    groups[group] = groups[group] || [];
    groups[group].push(o);
  });
  return Object.keys(groups).map(function(group) {
    return groups[group];
  });

  var result = groupBy(arr, function(i) {
    return currentObject.branch.id;
  })
}

var list = [{
  id: "102",
  name: "Alice"
}, {
  id: "205",
  name: "Bob",
  title: "Dr."
}, {
  id: "592",
  name: "Clyde",
  age: 32
}];

console.log(groupBy(list, function(i) {
  return i.id;
}));

它应该返回什么:

{
"102": [{id: "102", name: "Alice"}],
"205": [{id: "205", name: "Bob", title: "Dr."}],
"592": [{id: "592", name: "Clyde", age: 32}]
}

1 个答案:

答案 0 :(得分:3)

您只需要返回groups,而不在之前对该对象进行字符串化。



function groupBy(array, cb) {
    var groups = Object.create(null);
    array.forEach(function (o) {
        var key = cb(o);
        groups[key] = groups[key] || [];
        groups[key].push(o);
    });
    return groups;
}


var list = [{ id: "102", name: "Alice" }, { id: "205", name: "Bob", title: "Dr." }, { id: "592", name: "Clyde", age: 32 }];

console.log(groupBy(list, function (i) { return i.id; }));

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