undefinedfix
Sign in

How to combine and count array objects with the same attributes?

manarinian edited in Sun, 13 Nov 2022

Sample data structure:

 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
  }
]

Question: how to process data into the following data structures?

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
  }
]
4 Replies
ecisse
commented on Mon, 14 Nov 2022
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  
}, [])
slvrsky07
commented on Mon, 14 Nov 2022
  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]);
  }
  
blackace
commented on Mon, 14 Nov 2022
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])
Mr_MP
commented on Mon, 14 Nov 2022
// 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));