【数组分组】根据数组元素对象中的key值分组

根据数组元素对象中的key值分组

将下面数组中相同的tag的name和age 分组

在这里插入图片描述

var arr = [
      {tag: 'a', name: 1, age: 2},
      {tag: 'b', name: 3, age: 4},
      {tag: 'a', name: 5, age: 6},
      {tag: 'b', name: 7, age: 8},
      {tag: 'c', name: 7, age: 8},
      {tag: 'b', name: 1, age: 2},
      {tag: 'b', name: 3, age: 4},
      {tag: 'd', name: 5, age: 6},
      {tag: 'b', name: 7, age: 8},
      {tag: 'd', name: 7, age: 8},
    ]

    const groupBy = (arr, key, child) => 
      arr.reduce((t, v, i) => {
        let findIndex = t.concat().findIndex(e => e[key] === v.tag)
        if ( findIndex > -1) {
          t[findIndex][child] = t[findIndex][child].concat([{name: v.name, age: v.age}])
        } else {
          t.length += 1
          t[t.length - 1] = {}
          t[t.length - 1][key] = v[key]
          t[t.length - 1][child] = [].concat([{name: v.name, age: v.age}])
        }
        return t
      }, [])
      
// 根据相同的key的值分组
    console.log(groupBy(arr, 'tag', 'arr'))

结果为
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u010762099/article/details/88976495
今日推荐