7

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

  • 5
    Possible duplicate of [JavaScript set object key by variable](https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable) and literally hundreds of others – JJJ Nov 22 '17 at 17:46
  • 1
    You don't have a "JSON object". See [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – JJJ Nov 22 '17 at 17:47
  • Yes it is a Object Literal Notation – giththan giththan Nov 22 '17 at 18:11

4 Answers4

11

Try this one. This is works.

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

Gamsh
  • 545
  • 4
  • 21
10

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
}
CRice
  • 29,968
  • 4
  • 57
  • 70
2

This one is simple:

obj[id]=123;

Marek
  • 3,935
  • 10
  • 46
  • 70
  • its chows the result like `{first: 123, id: 23, second: 123}` but i want with out ` id: 23` in a efficient way – giththan giththan Nov 22 '17 at 17:53
  • I am not sure what exactly are you trying to do. So you want to change id: 23 to second: 123? Then add delete obj["id"]; before – Marek Nov 22 '17 at 18:25
1

Try:

obj[id] = 23

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

sofalse
  • 77
  • 1
  • 14