3 回答
TA贡献1836条经验 获得超13个赞
您可以使用reduce以替换从服务器获取的数据。
下面我模拟了不同的场景,考虑a作为原始数组和b&c作为来自服务器的响应
let a = [{ id: 1, selected: false, key: 'plan' }];
let b = [
{ id: 1, selected: true, key: 'plan', text: 'aaaa' },
{ id: 2, selected: true },
];
const mergeArrays = (array1, array2) => {
array2 = array2 || [];
array1 = array1 || [];
return Object.values([...array1, ...array2].reduce((result, obj) => {
result = {
...result,
[obj.id]: {...obj}
}
return result;
}, {}))
};
//Consider you got the response from server
//a -> Original array, b -> Response from serer
console.log(mergeArrays(a, b))
//Response from server is null or []
console.log(mergeArrays(a, null))
//original array is empty but there's a response from server
console.log(mergeArrays([], b))
//Consider there is completely a different object in the array received from the server than the one defined in the original array
let c = [{ id: 2, selected: true, key: 'plan' }];
console.log(mergeArrays(a, c))
.as-console-wrapper {
max-height: 100% !important;
}
TA贡献1946条经验 获得超3个赞
如果 b 大于 a,则必须首先确定哪个最大:
let a = [{id: 1, selected: false, key: "plan"}];
let b = [{id: 1, selected: true, key: "plan", "text": "aaaa"}, {id: 2, selected: true}];
let bigger = a.length > b.length ? a : b;
let shorter = a.length < b.length ? a : b;
console.log(bigger.map(x => ({...x, ...shorter.find(y => y.id === x.id)})))
添加回答
举报