将对象数组的每个元素乘以标量

时间:2018-07-24 12:32:11

标签: javascript arrays foreach

我有一个对象数组,每个对象也包含一些数组。

我想知道如何轻松访问这些值,例如将它们乘以一个常数。

可能需要forEach(),我试图这样做:

myArray = [{
    income: [1, 2, 3],
    outcome: [2, 3]
  },
  {
    income: [1, 9, 8, 5],
    outcome: [1, 3, 7]
  },
  {
    income: [7, 2, 8],
    outcome: [2, 6, 10]
  },
];

const myValue = 2;
myArray.forEach(ob => ob.income = ob.income * myValue, ob.outcome = ob.outcome * myValue);

在这种情况下,预期结果应为:

myArray = [
  {income: [2, 4, 6], outcome: [4, 6]},
  {income: [2, 18, 16, 10], outcome: [2, 6, 14]},
  {income: [14, 4, 16], outcome: [4, 12, 20]},
];

2 个答案:

答案 0 :(得分:2)

您可以简单地使用forEach()遍历所有对象,然后使用Array.map()获得所需的结果。

let myArray = [
            {income: [1, 2, 3], outcome: [2, 3]},
            {income: [1, 9, 8, 5], outcome: [1, 3, 7]},
            {income: [7, 2, 8], outcome: [2, 6, 10]},
];

const multiplyBy = 2;

myArray.forEach((obj)=>{
  obj.income = obj.income.map((a)=> a*multiplyBy);
  obj.outcome = obj.outcome.map((a)=> a*multiplyBy);
});

console.log(myArray);

答案 1 :(得分:1)

您可以获取所有属性并为新对象映射新属性。

var array = [{ income: [1, 2, 3], outcome: [2, 3] }, { income: [1, 9, 8, 5], outcome: [1, 3, 7] }, { income: [7, 2, 8], outcome: [2, 6, 10] }],
    factor = 2,
    result = array.map(o => 
        Object.assign(...Object.entries(o).map(([k, v]) =>
            ({ [k]: v.map(f => f * factor) }))));

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

更改原始数组

var array = [{ income: [1, 2, 3], outcome: [2, 3] }, { income: [1, 9, 8, 5], outcome: [1, 3, 7] }, { income: [7, 2, 8], outcome: [2, 6, 10] }],
    factor = 2;

array.forEach(o => 
    Object
        .entries(o)
        .forEach(([k, v]) => o[k] = v.map(f => f * factor))
);

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