1

I have a simple code like this:

var name = 'line1';
var obj = {};
obj.name = [0, 1];
console.log(obj);

Key of property is name. But I want to make key='line'. Can you help me?

2 Answers 2

6

If I understand correctly, and you want to use the value of the name variable as the property name, you can use this syntax:

obj[name] = [0, 1]; //obj.line1 will be [0, 1]

Object properties can also be accessed with the same syntax arrays use. It is handy in situations like this one.

Sign up to request clarification or add additional context in comments.

Comments

2

Try,

obj[name]

or

obj["line1"]

This is known as the bracket notation, and can be used to access any property of an object.

Comments

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.