# 如何將相同屬性的數組對象合併並統計個數

QQ: 2811132560

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

• 第一種解決辦法為最原始的，也是最原始的去重方式
``````  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));
``````
• 第二種解決辦法為將id當鍵值，判斷該鍵值是否存在，在去取value成數組
``````  let result = {};
for (let i = 0, len = data.length; i < len; i++) {
let dataArr = data[i];
if (result[dataArr.id]) {
result[dataArr.id].count ++;
} else {
result[dataArr.id] = { ...dataArr, count: 1 };
}
}
let resultArr = [];
for (const key in result) {
resultArr.push(result[key]);
}
console.log(JSON.stringify(Object.values(result), null, 2));
``````
• 第三種類似於第二種只不過是利用Object.entries將第二種對象轉為二維數組
``````  // reduce的4個參數 prev, cur, index, arr
var twoDimensionalArray = Object.entries(data.reduce((prev, cur) => {
if (!prev[cur.id]) {
prev[cur.id] = {
...cur,
count: 1
};
} else {
prev[cur.id].count += 1;
}
return prev;
}, {}));
var result = twoDimensionalArray.map(entry => entry[1]);
console.log(JSON.stringify(result, null, 2));
``````
• 第四種是用reduce方法對第一種方法進行精簡
``````  let result = 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;
}, []);
console.log(JSON.stringify(result, null, 2));
``````

2019與我的自由啟蒙