0

Please consider two thing before any comment/answer/vote

  1. Object is within array

  2. I know I can achieve it with constructor or function by binding this but I have a condition where I have to rewrite almost 100 lines of existing code just to achieve above functionality. I search almost everything and now asking from Java script Enthusiasts about all possible options with same domain Look at the below object.

Question:I just want total value to be equal to 7 which in current example is NAN

var demoObj = [{
    a: 2,
    b: 5,
    total: this.a * this.b 
}]

how I can achieve it? Please answer with any possible solution not matter how ugly code are I will manage.

Edit Someone try to mark it as duplicate to a given link in comments which is not true because there given answers not suite my needs. even in accepted answer there, if you change the value of a or b after initialization then total will change which not suite my case !

Abdul Hameed
  • 1,008
  • 1
  • 15
  • 35

1 Answers1

1

Can you use an IIFE or it is too ugly / out of the scope of your question?

var demoObj = [
  ((a, b) => ({ a, b, total: a * b }))(5, 2)
]

console.log(demoObj)
//  [
//    {
//      "a": 5,
//      "b": 7,
//      "total": 10
//    }
//  ]
0xc14m1z
  • 3,675
  • 1
  • 14
  • 23