简体   繁体   English

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

[英]Multiply each element of an array of an object by a scalar

I have an array of objects, each object containing some arrays too. 我有一个对象数组,每个对象也包含一些数组。

I wonder how can I access easily the values, for example, to multiply them by a constant. 我想知道如何轻松访问这些值,例如将它们乘以一个常数。

Probably there is a need for forEach() , I tried to do it like this: 可能需要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); 

The expected result, in this case, should be: 在这种情况下,预期结果应为:

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]},
];

You can simply use forEach() to iterate over all the objects and than use Array.map() to get the desired result. 您可以简单地使用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); 

You could take all properties and map new properties for new objects. 您可以采用所有属性并为新对象映射新属性。

 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; } 

Mutating the original array 突变原始数组

 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; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM