SA__
SA__

Reputation: 447

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

Upvotes: 5

Views: 13061

Answers (4)

Pranav C Balan
Pranav C Balan

Reputation: 115222

The push method is using to push an element to an array and not for adding a property to object.

You can use Object.assign for copying the value from an another object or directly set the property using dot or bracket notation.

Object.assign(data.user_data, {"name": "tom"})
// or
data.user_data.name = "tom";

var data = {
    "user_data": {
      "_id": "5806319c08756025b4c7287b",
      "email": "[email protected]",
      "password": "cool123",
    }
  },
  data1 = {
    "user_data": {
      "_id": "5806319c08756025b4c7287b",
      "email": "[email protected]",
      "password": "cool123",
    }
  };

Object.assign(data.user_data, {
    "name": "tom"
  })
  // or
data1.user_data.name = "tom";

console.log(data, data1);

Upvotes: 3

Bharat
Bharat

Reputation: 2464

Try like this, it will add your new key directly to your object

data.name = "tom";

Upvotes: 3

madalinivascu
madalinivascu

Reputation: 32354

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)

Upvotes: 10

Pasha K
Pasha K

Reputation: 407

simply)

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

and then

o.name = "tom"

Upvotes: 6

Related Questions