如何使用javascript在嵌套对象数组中按属性分配值

问题描述 投票:0回答:3

我想知道如何在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"
  }
]

javascript jquery arrays html5 object
3个回答
0
投票

我们可以使用reduce方法将数组减少到我们想要的结果。在这里,我在if方法的回调中添加了obj2条件和reduce中的映射值。基本上,在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);

1
投票

正如您的预期输出所示,您只需要id="insta"使用filter()的项目来获取这些项目。然后使用map()并在地图内创建一个临时对象。并使用Spread Operator返回组合对象。

注意:您需要创建另一个对象,因为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)

0
投票

首先,您可以使用Array.filter将数组id = "insta"包含对象,然后使用obj2Array.map中的数据应用于每个项目。

像这样的东西:

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)
© www.soinside.com 2019 - 2024. All rights reserved.