如何合并两个对象 TypeScript?

我有两个对象:


let a = [{id: 1, selected: false, key: "plan"}];

let b = [{id: 1, selected: true, key: "plan", "text": "aaaa"}, {id: 2, selected: true}];

我需要合并它们并获得:


let c = [{id: 1, selected: true, key: "plan", "text": "aaaa"}, {id: 2, selected: true}];

我的主要目的是在修改后重写默认对象


我努力了:


let c = {...a, ...b};


红颜莎娜
浏览 205回答 3
3回答

开心每一天1111

您可以使用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 sererconsole.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 serverconsole.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;}

智慧大石

如果 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;&nbsp;console.log(bigger.map(x => ({...x, ...shorter.find(y => y.id === x.id)})))

白板的微信

您可以使用解构:&nbsp;let c = [...a,...b];
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript