Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 280
giththan giththan Avatar asked Dec 03 '22 12:12

giththan giththan


2 Answers

Try this one. This is works.

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

like image 103
Gamsh Avatar answered Dec 05 '22 01:12

Gamsh


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
}
like image 21
CRice Avatar answered Dec 05 '22 01:12

CRice