3

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

1

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

In an object literal, each property name can only be identifier rather than an expression, which means you can't use variables. You can only use the square bracket notation on an existing object, so if you have a variable you wish to use as a property name then you'll need to do it after the object is created:

var object = {
    '1': {};
};

object[1][var_name_1] = 'value1';
object[1][var_name_2] = 'value2';

2 Comments

I don't want to have "multidimensial" object. I just want property NAME to be 'object[1][var_name_1]'.
In which case your first code sample will work. I'm not quite clear where the variable bit comes into it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.