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

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

可能需要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]},
];

最佳答案

您可以简单地使用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);

关于javascript - 将对象数组的每个元素乘以标量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51498720/

10-09 04:02