How to multiply values in objects in javascript

Viewed 1369

I'm trying to create a function where I can multiply the values of an object and return the sum.

for example:

let object = {
  'a': 4, 
  'b': 10,
  'c': 5
}

my code looks like this:

function sumOfValues(testObject) {
  let sumOfValues = (a * b * c)
  return sumOfValues
}


let testObject = {
  'a': 4, 
  'b': 10,
  'c': 5
}


sumOfValues(testObject)
4 Answers

You could get all values from the object and return the product of all values.

function productOfValues(object) {
    return Object.values(object).reduce((a, b) => a * b);
}

console.log(productOfValues({ a: 4, b: 10, c: 5 }));

The function works, but you missed the step where you use the object that is passed to the function.

If you always expect an object with a, b and c keys, then you could use an object destructuring assignment to use expose and use those keys inside the sumOfValues function.

function sumOfValues({ a, b, c }) {
  let sumOfValues = (a * b * c)
  return sumOfValues
}


let testObject = {
  'a': 4, 
  'b': 10,
  'c': 5
}


console.log(sumOfValues(testObject))


let object = {
  'a': 4, 
  'b': 10,
  'c': 5
}

let mult = 1;

for(let key of Object.keys(object)){
  mult *= object[key]
}

console.log(mult)

If the object has only 3 properties i.e. a,b,c then its straight forward,

const sumOfValues = (obj) => { return obj.a * obj.b * obj.c; }

But if the keys are variable and dynamic then you need the following,

const sumOfValues = (obj) => { 
    let sum = 1;
    Object.keys(obj).forEach(key => sum = sum*obj[key]);
    return sum;
}
Related