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

3

4 Answers 4

11

Try this one. This is works.

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

Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

2

This one is simple:

obj[id]=123;

2 Comments

its chows the result like {first: 123, id: 23, second: 123} but i want with out ` id: 23` in a efficient way
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
1

Try:

obj[id] = 23

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.