为了账号安全,请及时绑定邮箱和手机立即绑定

如何合并两个对象 TypeScript?

如何合并两个对象 TypeScript?

红颜莎娜 2022-10-27 16:30:14
我有两个对象: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};
查看完整描述

3 回答

?
开心每一天1111

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;

}


查看完整回答
反对 回复 2022-10-27
?
智慧大石

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)})))


查看完整回答
反对 回复 2022-10-27
?
白板的微信

TA贡献1883条经验 获得超3个赞

您可以使用解构: let c = [...a,...b];



查看完整回答
反对 回复 2022-10-27
  • 3 回答
  • 0 关注
  • 190 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信