1

I am trying to create a JSON object to store some parameters for a program. Some of the parameters need to be calculated from others as they are being defined. I would like to do this within the object definition but maybe this is not possible

var params = {
        a: 50,
        b: 70,
        c: this.a+this.b
    } 
Result

What happens

>params.c
NaN

What I wished happened

>params.c
120

Edit

After doing some further reading, I think I am using Object Literal Notation instead of JSON.

Cole
  • 600
  • 6
  • 12

3 Answers3

1

You can use this approach:

To avoid re-calculation, use the function Object.assign.

The get syntax binds an object property to a function that will be called when that property is looked up.

var params = {
  a: 50,
  b: 70,
  get c() {
    console.log('Called!');
    return this.a + this.b;
  }
};

console.log(params.c); // Prints 120 then Called!
console.log(params.c); // Prints 120 then Called!

var params = Object.assign({}, {
  a: 50,
  b: 70,
  get c() {
    console.log('Called from function Object.assign!');
    return this.a + this.b;
  }
});

params.a = 1000; // To illustrate.

console.log(params.c); // Prints 120
console.log(params.c); // Prints 120
.as-console-wrapper {
  max-height: 100% !important
}

Resources

Ele
  • 33,468
  • 7
  • 37
  • 75
0

Personally, I would create constants (since magic numbers are the devil), but this is an overly-simplistic example:

const FIFTY = 50;
const SEVENTY = 70;
var params = {
  a: FIFTY,
  b: SEVENTY,
  c: FIFTY + SEVENTY
};
th3n3wguy
  • 3,649
  • 2
  • 23
  • 30
0

What I would recommend doing is starting with an object that does not contain c, and taking the calculation outside of the object. Once the calculation has occurred, simply add the sum back to the object as a new key/value pair:

var params = {
  a: 50,
  b: 70,
}

var sum = 0;

for (var el in params) {
  if (params.hasOwnProperty(el)) {
    sum += params[el];
  }
}

params['c'] = sum;
console.log(params);
Ele
  • 33,468
  • 7
  • 37
  • 75
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71