我有两个JavaScript数组:
const array1 = [
{id: 01, qnty: 2},
{id: 02, qnty: 1},
{id: 03, qnty: 1}
];
const array2 = [{id: 02, qnty: 3}];
我希望输出为:
const newArray = [
{id: 01, qnty: 2},
{id: 02, qnty: 4},
{id: 03, qnty: 1},
];
输出数组应删除具有相同id
的项目,并将其qnty
值相加。
答案 0 :(得分:1)
function inArray(arr, obj) {
for (var i = 0; i < arr.length; i++) {
if (arr[i].id == obj.id) {
return i;
}
}
return -1;
}
const array1 = [{ id: 01, qnty: 2}, { id: 02,
qnty: 1}, { id: 03, qnty: 1}];
const array2 = [{ id: 02, qnty: 3}];
var newArray = array1.slice(0); //clone array1
for (var i = 0; i < array2.length; i++) {
var obj = array2[i];
var index = inArray(array1, obj);
if( index== -1){
newArray.push(obj);
}else {
newArray[index] = { id: newArray[index].id, qnty: newArray[index].qnty + obj.qnty }
}
}
console.log(newArray);
const newArray = [ {id: 01, qnty: 2}, {id: 02, qnty: 4}, {id: 03, qnty: 1}, ];