美文网首页
对象数组分组

对象数组分组

作者: 云上笔记 | 来源:发表于2020-07-14 18:50 被阅读0次

项目中成员列表需要按成员类型来显示,但是后台返回的列表数据格式不是我们遍历所需要的格式。
先把数据分组:

const agentList = [
  {
    "work_name": "张三",
    "agent_title": "店长"
  },
  {
    "work_name": "李四",
    "agent_title": "销售"
  },
  {
    "work_name": "小宝",
    "agent_title": "销售"
  },
  {
    "work_name": "刘怀",
    "agent_title": "顾问"
  },
  {
    "work_name": "李三",
    "agent_title": "顾问"
  }
];
let group = agentList.reduce((pre, item) => {
 pre[item.agent_title] = [...pre[item.agent_title] || [], item];
 return pre;
}, {});

执行上面代码,得到一个分好组的对象


分组.png

现在的数据格式还不能直接用于表格中遍历,所以还要再处理一下,把它变为一个数组

const finalGroups = Object.keys(groups).map(key=>{
    const obj = {
        name: key, 
        value: groups[key]
    };
    return obj;
});
图片.png

综上,把这个过程封装为一个函数

/**
 ** @param array: 对象数组
 ** @param groupParam: 对象数组中对象的键名
 ** @return result:按键名分组过的对象数组 
 */
function arrayGroupBy(array, groupParam) {
  const arr = array;
  const groupedArr = arr.reduce((pre, item) => {
    const groupName = item[groupParam];
    pre[groupName] = [...pre[groupName] || [], item];
    return pre;
  }, {});
  const result = Object.keys(groupedArr).map(key=>{
    const obj = {
        name: key, 
        value: groupedArr[key]
    };
    return obj;
  });
  return result;
}

相关文章

网友评论

      本文标题:对象数组分组

      本文链接:https://www.haomeiwen.com/subject/olyfhktx.html