3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超13個(gè)贊
您可以使用reduce以替換從服務(wù)器獲取的數(shù)據(jù)。
下面我模擬了不同的場(chǎng)景,考慮a作為原始數(shù)組和b&c作為來自服務(wù)器的響應(yīng)
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貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
如果 b 大于 a,則必須首先確定哪個(gè)最大:
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)})))
添加回答
舉報(bào)