所以,如果我有两个阵列......
const arr1 = [ { id: 1: newBid: true } ];
const arr2 = [ { id: 1, newBid: false }, { id: 2, newBid: false } ];
我想结束一个像这样的数组
[ { id: 1, newBid: false }, { id: 2, newBid: false } ]
但是......我希望{ id: 1, newBid: true }
来自arr1
而不是arr2
我正在使用Lodash uniqBy(arr1, arr2, ['id'])
,但它删除了第一次出现,而不是第二次出现
答案 0 :(得分:1)
您应该使用lodash mergeWith
功能。
const arr1 = [{
id: 1,
newBid: true
}];
const arr2 = [{
id: 1,
newBid: false
}, {
id: 2,
newBid: false
}];
function customizer(firstValue, secondValue) {
if(firstValue)
return firstValue;
else
return secondValue;
}
console.log(_.mergeWith(arr1, arr2, customizer));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>
答案 1 :(得分:0)
我发现使用对象作为地图是解决此类问题的最简单方法。
const arr1 = [ { id: 1, newBid: true } ];
const arr2 = [ { id: 1, newBid: false }, { id: 2, newBid: false } ];
const map = {};
function execute(array) {
for(let i = 0; i < array.length; i++) {
const item = array[i];
map[item.id] = item;
}
}
execute(arr1);
execute(arr2);
console.log(Object.values(map))