繁体   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