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

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

使用 javascript 更新對象值

使用 javascript 更新對象值

喵喵時光機 2021-08-20 10:18:51
我想知道如何使用 javascript 更新對象列表數組。如何更新objList與newObjList通過匹配id和name。如果id和name匹配,則更新objList嵌套數組對象。var result = updateObj(objList, newObjList);console.log(result);function updateObj(list, newObjList){  var flatarr = list.map(e=>Object.entries(e).map(([k, val]) => val)).flat(3);  var filterService =  newObjList.filter(e=>e.name=="service");  //got stuck}var newObjList=[{    "id": "service",    "name": "bank",    "amount": 2000},{    "id": "service",    "name": "credit",    "amount": 5000}]var objList=[{  "btob": [{    "id": "service",    "name": "bank",    "amount": 1000  },{    "id": "fund",    "name": "bank",    "amount": 2000  },{    "id": "others",    "name": "bank",    "amount": 5000   }]},{ "ctob":[{    "id": "service",    "name": "credit",    "amount": 1000,    "rate": 0.4  },{    "id": "fund",    "name": "credit",    "amount": 3000,    "rate": 0.2  },{    "id": "others",    "name": "credit",    "amount": 4000,    "rate": 0.6   }]  }]}]
查看完整描述

3 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

如果您想要一個完全不依賴于硬編碼的解決方案 - 即沒有"btob"或"ctob",您可以使用 a.map()來循環objList。對于其中的每個項目,循環遍歷它的所有鍵/值對,并使用.find(). 這也使您的原始對象保持原樣,而不是覆蓋它。


考慮下面的示例,其中我添加了一個額外的鍵來演示可擴展性。


var newObj = [

  { "id": "service", "name": "bank", "amount": 2000 },

  { "id": "service", "name": "credit", "amount": 5000 },

  { "id": "test", "name": "test", "newKey": "Hello world!"}

]; 

var objList = [

  { "btob": [{ "id": "service", "name": "bank", "amount": 1000 },{ "id": "fund", "name": "bank", "amount": 2000 },{ "id": "others", "name": "bank", "amount": 5000 }] },

  { "ctob":[{ "id": "service", "name": "credit", "amount": 1000, "rate": 0.4 },{ "id": "fund", "name": "credit", "amount": 3000, "rate": 0.2 },{ "id": "others", "name": "credit", "amount": 4000, "rate": 0.6 }]}, 

  { "dtob": [{ "id": "test", "name": "test"}]}

];


let result = objList

  .map(root => Object.keys(root)

    .reduce((output,key) => (

      {...output, [key]: root[key]

        .flatMap(i => {

          let replacement = newObj.find(f => i.id === f.id && i.name === f.name);

          return replacement ? {...i, ...replacement} : i;

        })

      }

    ), {})

  );


console.log(result);


查看完整回答
反對 回復 2021-08-20
  • 3 回答
  • 0 關注
  • 458 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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