Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply object values in es6

ok so im have a variable filled with a object and the object has key value pairs now heres the code !

var images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];
var areas = [];

//calculate the are of hte image 

images.forEach((image)=>{
    areas.push(images.height.value*images.width.value)
});

im trying to run threw the object and multiply the values and add them to the new areas array !

like image 423
JimClayton Avatar asked Sep 09 '17 15:09

JimClayton


People also ask

How do you multiply values in Javascript?

The Multiplication Operator ( * ) multiplies numbers.


1 Answers

You don't need the value property, and you have to use the argument from what you're iterating over, i.e. image in each iteration.

You could use Array.map to return the values directly to a new array, and Array.reduce if you want to sum the values

var images = [
  { height: 10, width: 30 },
  { height: 20, width: 90 },
  { height: 54, width: 32 }
];

var areas = images.map( img => img.height * img.width);
var total = areas.reduce( (a,b) => (a+b) );

console.log(areas);
console.log(total);
like image 164
adeneo Avatar answered Oct 13 '22 01:10

adeneo