我如何基于javascript中的值对数组进行分组?

时间:2019-02-14 03:01:39

标签: javascript arrays

我有以下数组

array1 = [{
    category: "Age"
    id: "11"
  },
  {
    category: "Gender"
    id: "M"
  },
  {
    category: "Age"
    id: "23"
  },
  {
    category: "Gender"
    id: "F"
  },
  {
    category: "Education"
    id: "Graduate"
  },
  {
    category: "Age"
    id: "55"
  }
]

我希望它按类别分组,类似这样

groupedArray = [{
  category: "Age",
  groupedCat: [{
      category: "Age"
      id: "11"
    },
    {
      category: "Age"
      id: "23"
    },
    {
      category: "Age"
      id: "55"
    }
  ],
  category: "Gender",
  groupedCat: [{
      category: "Gender"
      id: "M"
    },
    {
      category: "Gender"
      id: "F"
    }
  ],
  category: "Education",
  groupedCat: [{
    category: "Education"
    id: "Graduate"
  }]
}]

1 个答案:

答案 0 :(得分:0)

您可以这样做:

var array1 = [{
  category: "Age",
  id: "11"
}, {
  category: "Gender",
  id: "M"
}, {
  category: "Age",
  id: "23"
}, {
  category: "Gender",
  id: "F"
}, {
  category: "Education",
  id: "Graduate"
}, {
  category: "Age",
  id: "55"
}];

let res = {};
for (var o of array1) {
  if (res[o.category] === undefined) {
    res[o.category] = [];
  }
  res[o.category].push(o);
}
console.log(res);

请注意,这与您在上面的问题中所要求的不完全相同,我改用category作为对象的键。我认为这就是您要寻找的。如果没有发表评论,我可以更新。

希望这会有所帮助