Alex Pliutau
Alex Pliutau

Reputation: 21957

Add property to object with key in JavaScript

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

Answers (2)

Anurag
Anurag

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

kapa
kapa

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

Related Questions