1、比较两个数组对象,取出不同的值
var array1 = [ {"Num": "A " },{"Num": "B" }];
var array2 = [ {"Num": "A ","Name": "t1 " }, {"Num": "B","Name": "t2"}, {"Num": "C " ,"Name": "t3 "}];
var result = [];
for(var i = 0; i < array2.length; i++){
var obj = array2[i];
var num = obj.Num;
var isExist = false;
for(var j = 0; j < array1.length; j++){
var aj = array1[j];
var n = aj.Num;
if(n == num){
isExist = true;
break;
}
}
if(!isExist){
result.push(obj);
}
}
console.log(result);
2、合并数组中的对象某一相同的字段名,并统计合并某一指定字段的和;组成新的数组;
var that.shopdata=[
{item_id:'73',total:1,item:{title:'荔枝',startn:2}},
{item_id:'73',total:2,item:{title:'荔枝',startn:2}},
{item_id:'74',total:6,item:{title:'荔枝',startn:33}},
{item_id:'73',total:1,item:{title:'荔枝',startn:2}},
{item_id:'73',total:3,item:{title:'荔枝',startn:2}},
{item_id:'71',total:1,item:{title:'sss',startn:2}},
]
let newfood=[];//形同字段名组成的新数组;
var temp = {};//组合数组中的对象某个字段名相同情况下的数量和;
for(var s in that.shopdata) {
var key= that.shopdata[s].item_id;
if(temp[key]) {
temp[key].item_id = temp[key].item_id ;
temp[key].total = temp[key].total+ that.shopdata[s].total;
} else {
temp[key] = {};
temp[key].item_id = that.shopdata[s].item_id;
temp[key].total = that.shopdata[s].total;
}
if(that.shopdata[s].item.startn){
temp[key].startn=that.shopdata[s].item.startn;
}
temp[key].title=that.shopdata[s].item.title;
}
for(var k in temp){ //循环组成新数组;
newfood.push(temp[k])
}