javascript - 怎么把数组中的有规律的多个对象合并成一个?
本文介绍了javascript - 怎么把数组中的有规律的多个对象合并成一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
[{
method:'fly',
code:'1',
count:1,
},{
method:'fly',
code:'1',
count:2,
}]
[{
method:'fly',
code:'1',
count:3,//count相加了
}]
自己实现了一个,不知道有么有bug,求指点
function mergeOrder(order) {
return order.reduce((a, b) => {
let flag = a.some((item, index) => {
return item.method === b.method && item.code === b.code;
});
if (flag) {
for (let item of a) {
if (item.method === b.method && item.code === b.code) {
item.count += b.count;
}
}
} else {
a.push(b);
}
return a;
}, [{
method: '',
code: '',
count: 0
}]);
}
解决方案
如下,result是你想要得到的数组:
var result = [];
var arr = [{
method:'fly',
code:'1',
count:1,
},{
method:'fly',
code:'1',
count:2,
}];
for(var i =0; i< arr.length; i++){
var isFind = false;
for(var j =0 ; j< result.length; j++){
if(arr[i].method === result[j].method && arr[i].code === result[j].code){
result[j].count += arr[i].count;
isFind = true;
break;
}
}
if(!isFind)
result.push(arr[i]);
}
这篇关于javascript - 怎么把数组中的有规律的多个对象合并成一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文