亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何合并兩個對象 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 關注
  • 250 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號