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

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

如果條件 (JavaScript ES6),則將一個特定對象 prop 從一個數組移動到另一個

如果條件 (JavaScript ES6),則將一個特定對象 prop 從一個數組移動到另一個

慕的地6264312 2023-09-21 17:19:19
我有 2 個從 2 個不同的 fetch 返回的對象數組const result1 = [  {    name: 'matteo',    age: 20,    id: 1,  },  {    name: 'luca',    age: 24,    id: 2,  },];const result2 = [  {    warnings: 'yes',    hobby: "tennis",    id: 1,  },  {    warnings: 'many',    hobby: "ping pong",    id: 2,  },];這是我當前的方法,但如果它們具有相同的 id,它將合并從 result2 到 result1 的整個對象const t = result2.reduce((acc, curr) => {    acc[curr.id] = curr;    return acc;  }, {});  const d = result1.map((d) =>    Object.assign(d, t[d.id])   );目前的結果是:{    name: 'matteo',    age: 20,    id: 1,warnings: "yes",hobby: "tennis"  },  {    name: 'luca',    age: 24,    id: 2,warnings: "many",hobby: "ping pong"  },我只想將 warnings 屬性從第二個對象數組移動到第一個對象數組,其中對象 id 相等期望的輸出:const result3 = [      {        name: 'matteo',        age: 20,        id: 1,        warnings: "yes"      },      {        name: 'luca',        age: 24,        id: 2,        warnings: "many"      },    ];
查看完整描述

1 回答

?
慕工程0101907

TA貢獻1887條經驗 獲得超5個贊

您可以使用它map來創建一個新數組,并find獲取具有匹配 id 的任何警告:


let result1 = [

  { id: 1, name: 'a', age: 1 },

  { id: 2, name: 'b', age: 2 },

  { id: 3, name: 'c', age: 3 },

  { id: 4, name: 'd', age: 4 }

];


let result2 = [

  { id: 1, hobby: 'aa', warnings: 'aaa' },

  { id: 2, hobby: 'bb', warnings: 'bbb' },

  { id: 4, hobby: 'dd', warnings: 'ddd' }

];


let includeWarnings = (data, warningsArr) => data.map(obj => {

  

  // `w` will be undefined if no matching warning is found

  let w = warningsArr.find(warn => warn.id === obj.id);

  

  // Return all the data in `obj`, and the "warnings" property

  // of `w` if `w` is defined

  return { ...obj, ...(w ? { warnings: w.warnings } : {}) };

  

});

console.log(includeWarnings(result1, result2));

請注意,如果您的數據格式是在考慮映射的情況下構建的,那么您的情況可能會更好id:


let result1 = {

  id1: { name: 'name1', age: 1 },

  id2: { name: 'name2', age: 2 },

  .

  .

  .

}


let result2 = {

  id1: { hobby: 'hobby1', warnings: 'warnings1' },

  id2: { hobby: 'hobby2', warnings: 'warnings2' },

  .

  .

  .

}


查看完整回答
反對 回復 2023-09-21
  • 1 回答
  • 0 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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