SA__ SA__ - 1 month ago 5
jQuery Question

Pushing new key value pair to json

Here is my Json output

"user_data": {
"_id": "5806319c08756025b4c7287b",
"email": "a@adsfd.com",
"password": "cool123",
}


How can i add a new key value pair so that i can get

"user_data": {
"_id": "5806319c08756025b4c7287b",
"email": "a@adsfd.com",
"password": "cool123",
"name" : "tom"
}


I tried like this

data.push({"name": "tom"});


But i am always getting the

"user_data": {
"_id": "5806319c08756025b4c7287b",
"email": "a@adsfd.com",
"password": "cool123",
}


How can i do this. Help pls

Answer

You want to append to user_data not the whole object another object

Try using the array notation

data["user_data"]["name"] = "tom";

or

data.user_data.name = "tom";

demo:

data = {"user_data": {
    "_id": "5806319c08756025b4c7287b",
    "email": "a@adsfd.com",
    "password": "cool123",
  }};
  
  data["user_data"]["name"] = "tom";
  console.log(data)

Comments