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

时间:2019-04-24 07:40:54

标签: javascript jquery arrays html5 object

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

3 个答案:

答案 0 :(得分:1)

如您的预期输出所示,您只需要id="insta"的物品,因此请使用filter()来获得它们。然后使用map()并在map中创建一个临时对象。然后使用Spread运算符返回合并的对象。

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

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)

答案 1 :(得分: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);

答案 2 :(得分:0)

首先,您可以Array.filter将数组包含在id = "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)