最近做项目遇到一个需求,具体就是统计对象数组中某个对象的属性相同的放入到一起,和数组去重有点类似但是又不太一样,我想到了用es6的reduce方法,轻松解决,废话不多说上代码
let tempData = [
{count: 10, itemName: 'test01'},
{count: 20, itemName: 'test01'},
{count: 30, itemName: 'test02'},
{count: 40, itemName: 'test03' }
]
let newData = tempData.reduce(
(prev, current, index, arr) => {
let temObj = {
};
let hasValue = prev.findIndex((item) => {
return item.name === current.itemName;
});
if (hasValue == -1) {
temObj.name = current.itemName;
temObj.data = [current.count];
prev.push(temObj);
}
if (hasValue != -1) {
prev[hasValue].data = prev[hasValue].data.concat(current.count);
}
return prev;
},
[]
);