js 数组对象根据指定key合并数组

const list = [
{
name:'111',
data:10,
},
{
name:'111',
data:60,
},
{
name:'222',
data:20,
},
{
name:'222',
data:30,
},
]
  mergeArr(arr, key) {
        var afterData = []
        arr.forEach((item) => {
          const flag = afterData.find((item1) => item1[key] === item[key])
          if (!flag) {
            const obj = {}
            obj[key] = item[key]
            obj['data'] = [item]
            afterData.push(obj)
          } else {
            flag.data.push(item)
          }
        })
        return afterData
      }
 console.log(mergeArr(list,'name'))

你可能感兴趣的:(js 数组对象根据指定key合并数组)