Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using function parameter value as dictionary key

Attempting to build a dictionary using key that comes via function parameter.

var progres_mark = function(progress_state) {
  var now = Date();
  console.log({ progress_state : now })
}

progres_mark("encode")

Expected

{ 'encode': 'Sun Oct 19 2014 18:22:33 GMT+0300 (IDT)' }

Actual

{ progress_state: 'Sun Oct 19 2014 18:22:33 GMT+0300 (IDT)' }

What’s going on?

like image 530
Maxim Veksler Avatar asked Jun 24 '26 09:06

Maxim Veksler


1 Answers

Because the compiler only expects an identifier or a string and therefore will not evaluate to the variable's value. But you can use bracket notation to achieve what you want.

var progres_mark = function(progress_state) {
  var now = Date();
  var obj = {}; obj[progress_state] = now;
  console.log(obj)
}
like image 121
Amit Joki Avatar answered Jun 26 '26 23:06

Amit Joki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!