在JavaScript中按数组属性分组

时间:2018-05-01 01:07:45

标签: javascript

如果我有这样的数组:

var arr = [
    { id: 1 , name: "James"},
    { id: 2, name: "John"},
    { id: 1, name: "Jake"}
]

如何按属性进行分组,如下所示:

{ id: 1, name: "James", "Jake" },
{ id: 2, name: "John"}

3 个答案:

答案 0 :(得分:3)

通常,当您尝试按单个值进行分组时,可以将某些内容添加到某种散列中 - 可以是javascript对象或Map。因为这些数据类型的键需要是唯一的,所以可以很容易地将它们组合在一起。

例如,这使用一个对象来拉取一个键下的所有ID。然后使用Object.values()返回和数组:



var arr = [{ id: 1 , name: "James"},{ id: 2, name: "John"},{ id: 1, name: "Jake"}]
let hash = arr.reduce((a,c) => {
    // a is an object passed into reduce
    // if it already has a key for c.id just push into the name array
    if (a[c.id]) a[c.id]['name'].push(c.name)
    // if not, add a key for c.id and set it to an object
    // with and id and name array
    else a[c.id] = {id: c.id, name:[c.name]}
    return a
    }, {}) // <-- this {} becomes 'a' (for accumulator) in the reduce loop

// now if you want an array, just take the values
newObj = Object.values(hash)
console.log(hash)
console.log(newObj)
&#13;
&#13;
&#13;

答案 1 :(得分:2)

假设您需要一组名称,可以使用函数reduce按名称id对名称进行分组。

const arr = [    { id: 1 , name: "James"},    { id: 2, name: "John"},    { id: 1, name: "Jake"}],
      result = Object.values(arr.reduce((a, {id, name}) => {
        (a[id] || (a[id] = {id, name: []})).name.push(name);
        return a;
      }, {}));
      
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:0)

您可以使用lodash groupBy方法来完成此任务。请在https://lodash.com/docs/4.17.10#groupBy

查看_.groupBy文档

请记住,您需要完全安装lodash,您只能安装所需的方法https://lodash.com/custom-builds