Reputation: 21957
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?
Upvotes: 1
Views: 359
Reputation: 141859
Try,
obj[name]
or
obj["line1"]
This is known as the bracket notation, and can be used to access any property of an object.
Upvotes: 2
Reputation: 78671
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.
Upvotes: 6