如何从数组对象中添加两个键值并在第一个键中更新?

时间:2019-03-20 11:42:10

标签: javascript arrays object javascript-objects

我有两个对象组成的数组:

let abc = [
  {amount: 1000, rate: 4},
  {amount: 100,  rate: 2},
  {amount: 700,  rate: 1}
];

我想乘amount * rate并用amount键更新。

预期输出:

let output = [
  {amount: 4000, rate: 4},
  {amount: 200,  rate: 2},
  {amount: 700,  rate: 1}
];

4 个答案:

答案 0 :(得分:4)

您可以简单地使用.map()

let data = [{amount: 1000, rate: 4}, {amount: 100, rate: 2},{amount: 700, rate: 1}];

let result = data.map(o => ({...o, amount: o.amount * o.rate}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

使用Array.prototype.map()

   let abc = [{amount: 1000, rate: 4}, {amount: 100, rate: 2}, {}, {amount: 700, rate: 1}]
   abc.map(x => {
       if(!x.amount || !x.rate){  // account for empty objects
           return x;
       }
       return {...x, amount: x.amount * x.rate}
   });

答案 2 :(得分:0)

let abc = [{amount: 1000, rate: 4}, {amount: 100, rate: 2},{amount: 700, rate: 1}]
var output = abc.map(field => {
field.amount = field.amount * field.rate
return field
})
console.log(output)

答案 3 :(得分:0)

如果您不想创建新的数组,则可以使用forEach。

let abc = [
  {amount: 1000, rate: 4},
  {amount: 100,  rate: 2},
  {amount: 700,  rate: 1}
];

abc.forEach(item => item.amount = item.amount * item.rate)

console.log(abc)