0

I need to find sum of all property values and save it into another (totalScore) property of the same object

What I have tried:

Below function is tested and returns sum of all object properties except totalScore (or k = any property) property.

const calculateScore = (my_object) => {
  const allowed = Object.keys(my_object).reduce((obj, k) => {
    if (k != 'totalScore') obj[k] = my_object[k];
    return obj;
  }, {});

  return Object.values(allowed).reduce((a, b) => a + b);
}

Let's say I have this object:

const obje = {
  prop1: 1,
  prop2: 2,
  prop3: 3,
  totalScore: calculateScore(this)
}

I tried just invoking calculateScore function above and received a Function as totalScore, moreover this keyword is pointing to a Global object.

I also tried IIFE, so totalScore runs whenever Object (and its constructor) is created:

const obje = {
  prop1: 1,
  prop2: 2,
  prop3: 3,
  totalScore: (() => calculateScore(this))()
}

But still no success. I would like this way to work and or would be glad to see a better implementation of my use case.

koloml
  • 360
  • 1
  • 11
Rasul
  • 1

0 Answers0