如何将相同属性的数组对象合并并统计个数?

示例数据结构:

 let data = [{
    id: '1',
    goodsName: 'test',
    price: 22
  },
  {
    id: '2',
    goodsName: 'test',
    price: 22
  },
  {
    id: '2',
    goodsName: 'test',
    price: 22
  },
  {
    id: '3',
    goodsName: 'test',
    price: 22
  },
  {
    id: '3',
    goodsName: 'test',
    price: 22
  },
  {
    id: '3',
    goodsName: 'test',
    price: 22
  },
  {
    id: '3',
    goodsName: 'test',
    price: 22
  },
  {
    id: '4',
    goodsName: 'test',
    price: 22
  }
]

问题:如何将数据处理为下列数据结构?

let data = [{
    id: '1',
    goodsName: 'test',
    price: 22,
    count:1
  },
  {
    id: '2',
    goodsName: 'test',
    price: 22,
    count:2
  },
  {
    id: '3',
    goodsName: 'test',
    price: 22,
    count:4
  },
  {
    id: '4',
    goodsName: 'test',
    price: 22,
    count:1
  }
]
阅读 411
评论 2019-12-30 提问
    4 个回答
    data.reduce((obj, item) => {  
      let find = obj.find(i => i.id === item.id)  
      let _d = {  
        ...item,  
        count: 1  
      }  
      find ? find.count++ : obj.push(_d)  
      return obj  
    }, [])
    评论 赞赏 2019-12-30
        let dataArr = [你的那个数组]
        let result = {};
        for (let i = 0, len = dataArr.length; i < len; i++) {
          let data = dataArr[i];
          if (result[data.id]) {
            result[data.id]["count"] += 1;
          } else {
            result[data.id] = { ...data, count: 1 };
          }
        }
        let resultArr = [];
        for (const key in result) {
          resultArr.push(result[key]);
        }
        
      评论 赞赏 2019-12-30
        Yooloo
        • 778
        Object.entries(data.reduce((a,c)=>{
          if(!a[c.id]){
            a[c.id] = {
                ...c,
                count:1
            }
          }else{
            a[c.id].count += 1;
          }
          return a;
        },{})).map(entry=>entry[1])
        评论 赞赏 2019-12-30
          琴亭夜雨
          • 3
          • 新人请关照
          // 1th Method
          var interimArray = [];   // 用来存放去重后的id的
          var resultArray = [];   // 最终的期望结果
          
          var count = 1;
          for (var i in data) {
            if (interimArray.indexOf(data[i].id) > -1) {
              console.log(`${data[i].id}已经存在,计数加1`, `count为${count}`);
              for (var j in resultArray) {
                if (resultArray[j].id === data[i].id) {
                  count++;
                  resultArray[j].count = count;
                }
              }
            } else {
              count = 1;
              console.log(`${data[i].id}不存在,数组加入${data[i].id}`, `count重置为${count}`);
              interimArray.push(data[i].id);
              data[i].count = count;
              resultArray.push(data[i]);
            }
          }
          
          console.log(JSON.stringify(resultArray, null, 2));
          评论 赞赏 1月3日
            撰写回答

            登录后参与交流、获取后续更新提醒