簡體   English   中英

如何使用JavaScript在嵌套對象數組中按屬性分配值

[英]How to assign values by property in nested object array using javascript

我想知道如何通過JavaScript中的id=insta將值分配給嵌套對象中的對象屬性

我有兩個對象,我需要使用javascript將一個對象屬性應用於另一個

我被卡住了,不知道如何進行,

obj1.forEach(e=> {if(e.id==='insta') Object.assign(e, obj2)})
var obj1 = [
  {
    id: "insta",
    rate: "2.4",
    fee: "0",
    amount: "400"
  },
 {
    id: "trans",
    rate: "1.4",
    fee: "0",
    amount: "200"
  }
]

var obj2 = 
{
  data: {
     rate_value: "4.4",
     fee_value: "10",
     targetamount: "5000",
     country_code: "SG"
   }
}

Expected Output: 

res= [
  {
    id: "insta",
    rate: "4.4",
    fee: "10",
    amount: "5000",
    country_code: "SG"
  }
]

如預期的輸出所示,您只需要id="insta"的項目,因此請使用filter()來獲取它們。 然后使用map()在map中創建一個臨時對象。 然后使用Spread運算符返回合並的對象。

注意:您需要創建另一個對象,因為obj2和array中的屬性名稱不同。

 var obj1 = [ { id: "insta", rate: "2.4", fee: "0", amount: "400" }, { id: "trans", rate: "1.4", fee: "0", amount: "200" }] var obj2 = { data: { rate_value: "4.4", fee_value: "10", targetamount: "5000", country_code: "SG" } } const res = obj1.filter(x => x.id === "insta").map(x => { const {data} = obj2 let temp = { rate : data.rate_value, fee : data.fee_value, amount : data.targetamount, country_code : data.country_code } return {...x,...temp} }) console.log(res) 

我們可以使用reduce方法將數組縮小為我們想要的結果。 在這里,我在reduce方法的回調中添加obj2if條件和映射值。 基本上,在reduce回調方法中完成了過濾和映射。

 var obj1 = [{ id: "insta", rate: "2.4", fee: "0", amount: "400" }, { id: "trans", rate: "1.4", fee: "0", amount: "200" } ] var obj2 = { data: { rate_value: "4.4", fee_value: "10", targetamount: "5000", country_code: "SG" } } const result = obj1.reduce((acc, curr) => { if (curr.id === 'insta') { acc.push({ ...curr, rate: obj2.data.rate_value, fee: obj2.data.fee_value, amount: obj2.data.targetamount, country_code: obj2.data.country_code }) } return acc; }, []); console.log(result); 

首先,您可以Array.filter數組以包含id = "insta" insta”的對象,然后使用Array.mapobj2的數據應用於每個項目。

像這樣:

 var obj1 = [{ id: 'insta', rate: '2.4', fee: '0', amount: '400', }, { id: 'trans', rate: '1.4', fee: '0', amount: '200', }, ]; var obj2 = { data: { rate_value: '4.4', fee_value: '10', targetamount: '5000', country_code: 'SG', }, }; const result = obj1 .filter(item => item.id === 'insta') .map(item => ({ id: item.id, rate: obj2.data.rate_value, fee: obj2.data.fee_value, amount: obj2.data.targetamount, country_code: obj2.data.country_code, })); console.log(result) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM