Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pushing new key value pair to json

Here is my Json output

 "user_data": {
    "_id": "5806319c08756025b4c7287b",
    "email": "[email protected]",
    "password": "cool123",
  }

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

 "user_data": {
    "_id": "5806319c08756025b4c7287b",
    "email": "[email protected]",
    "password": "cool123",
    "name" : "tom"
  }

I tried like this

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

But i am always getting the

 "user_data": {
    "_id": "5806319c08756025b4c7287b",
    "email": "[email protected]",
    "password": "cool123",
  }

How can i do this. Help pls

like image 833
SA__ Avatar asked Dec 06 '22 16:12

SA__


2 Answers

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": "[email protected]",
    "password": "cool123",
  }};
  
  data["user_data"]["name"] = "tom";
  console.log(data)
like image 96
madalinivascu Avatar answered Dec 14 '22 06:12

madalinivascu


simply)

  o = {
    "_id": "5806319c08756025b4c7287b",
    "email": "[email protected]",
    "password": "cool123",
  }

and then

o.name = "tom"
like image 27
Pasha K Avatar answered Dec 14 '22 07:12

Pasha K