Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript expression to define object's property name?

Tags:

javascript

I'd like to create this object...

object = {
  'object[1][var_name_1]' : 'value1',
  'object[1][var_name_2]' : 'value2',
};

I'm trying to it this way, but I'm getting error missing : after property id...

function getPrefix() {
  return 'object[1]';
}

object = {
  getPrefix() + '[var_name_1]' : 'value1',
  getPrefix() + '[var_name_2]' : 'value2',
}

What am I doing wrong? Or maybbe it is impossible to set object property name using js experession?

Thank you

like image 972
Kirzilla Avatar asked May 10 '26 02:05

Kirzilla


1 Answers

You cant set variable properties using literal syntax, but you can set properties using [], after you've created the object:

myObject = {}
myObject["any_string_here"] = myValue
like image 88
Jakob Avatar answered May 11 '26 15:05

Jakob



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!