how to add key value pair in the JSON object already declared

29

I have declared a JSON Object and added some key value pair in that like:

var obj  = {};

and added some data into it like:

obj = {
"1":"aa",
"2":"bb"
};

But I want to add more key value pair in the same object, if I add key value pair same above mentioned then it replace the old one. So could any one please tell me how I can append data in the same JSON Object i.e. obj.

This question is tagged with javascript json

~ Asked on 2015-02-15 15:30:38

The Best Answer is


59

Could you do the following:

obj = {
    "1":"aa",
    "2":"bb"
};


var newNum = "3";
var newVal = "cc";


obj[newNum] = newVal;



alert(obj["3"]); // this would alert 'cc'

~ Answered on 2015-02-15 15:49:39


11

You can use dot notation or bracket notation ...

var obj = {};
obj = {
  "1": "aa",
  "2": "bb"
};

obj.another = "valuehere";
obj["3"] = "cc";

~ Answered on 2015-02-15 15:42:41


Most Viewed Questions: