giththan giththan
giththan giththan

Reputation: 93

How to add variable as json key in javaScript

I have a json object with key value pair. I want to add a variable as key but i dont know how to add. I tried with some code but it dosen't set the variable value. How can i solve this?

var id='second'
var obj={'first': 123, id: 23}
console.log(obj); //{first: 123, id: 23}

But i want to be the result like this.

{first: 123, second: 23}

Please help me to fix this problem. Thankyou

Upvotes: 7

Views: 4677

Answers (4)

Gamsh
Gamsh

Reputation: 545

Try this one. This is works.

id='second'
var obj={'first': 123,[id]: 23}

Upvotes: 11

CRice
CRice

Reputation: 32146

If you have built the object already, you can add the property by

obj[id] = 23

If you have not built the object and are putting it together at that moment:

var obj = {
    first: 123,
    [id]: 23
}

Upvotes: 10

Marek
Marek

Reputation: 4081

This one is simple:

obj[id]=123;

Upvotes: 2

sofalse
sofalse

Reputation: 77

Try:

obj[id] = 23

It'll add a key named by the value of variable id and set its value to 23.

Upvotes: 1

Related Questions