两个数组,重复的属性覆盖,不重复的添加
问题描述:
B2B后台:关于添加商品的问题,添加一些商品,如果添加的商品在原商品中存在,则覆盖其数量,不存在则添加
例:arr1 = [ {"externalCommodityCode" : "690123456001","commodityCode" : "200010825","saleAmount" : 20.0},
{"externalCommodityCode" : "690123456002","commodityCode" : "200010826","saleAmount" : 10.0,} ]
arr2 = [ {"externalCommodityCode" : "690123456002","commodityCode" : "200010826","saleAmount" : 20.0},
{"externalCommodityCode" : "690123456003","commodityCode" : "200010827","saleAmount" : 10.0} ]
最后得到 => arr1 = [ {"externalCommodityCode" : "690123456001","commodityCode" : "200010825","saleAmount" : 20.0},
{"externalCommodityCode" : "690123456002","commodityCode" : "200010826","saleAmount" : 20.0},
{"externalCommodityCode" : "690123456003","commodityCode" : "200010827","saleAmount" : 10.0,} ]
arr2.forEach(item => { let num = 0 arr1.some(val => { num++ if (val.externalCommodityCode === item.externalCommodityCode) { val.saleAmount = item.saleAmount return true } else if (num === arr1.length) { arr1.push(Object.assign({}, item)) } }) })