第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何合并兩個(gè)對(duì)象 TypeScript?

如何合并兩個(gè)對(duì)象 TypeScript?

紅顏莎娜 2022-10-27 16:30:14
我有兩個(gè)對(duì)象: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}];我的主要目的是在修改后重寫默認(rèn)對(duì)象我努力了:let c = {...a, ...b};
查看完整描述

3 回答

?
開心每一天1111

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;

}


查看完整回答
反對(duì) 回復(fù) 2022-10-27
?
智慧大石

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


查看完整回答
反對(duì) 回復(fù) 2022-10-27
?
白板的微信

TA貢獻(xiàn)1883條經(jīng)驗(yàn) 獲得超3個(gè)贊

您可以使用解構(gòu): let c = [...a,...b];



查看完整回答
反對(duì) 回復(fù) 2022-10-27
  • 3 回答
  • 0 關(guān)注
  • 256 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)