JavaScript SAO操作 之 对数组对象进行分组

179 阅读1分钟

一、前言

对以下数据按 city 字段分组:

userInfo: [
    {
        city: "yyds",
        idNumber: "510000000000000000",
        cellphone: "15111111111",
    },
    {
        city: "yyds",
        idNumber: "511111111111111111",
        cellphone: "13222222222",
    },
    {
        city: "xswl",
        idNumber: "522222222222222222",
        cellphone: "17111111111",
    },
],

二、解决方案

方案一(手写方法):

  • 代码
const groups = {};
userInfo.forEach((item) => {
  const group = JSON.stringify(item.city);
  groups[group] = groups[group] || [];
  groups[group].push(item);
});
console.log("方案一:", groups);
  • 效果

image.png

方案二 (lodash)

  • 安装依赖包 npm install lodash --save
  • 代码
// 引入依赖包
import _ from "lodash";

// 分组
const groups = _.chain(userInfo)
  .groupBy("city")
  .toPairs()
  .map(function (currentItem) {
    return _.fromPairs(_.zip(["city", "userInfo"], currentItem));
  })
  .value();
console.log("方案二:", groups);
  • 效果

image.png

三、小结

实现数据分组的方式多种多样,我目前用到的就这两种。