Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 728
MaxSteel Avatar asked Feb 15 '15 15:02

MaxSteel


People also ask

Does JSON have key-value pairs?

A JSON object contains zero, one, or more key-value pairs, also called properties. The object is surrounded by curly braces {} . Every key-value pair is separated by a comma.


2 Answers

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' 
like image 100
scgough Avatar answered Sep 21 '22 20:09

scgough


You can use dot notation or bracket notation ...

var obj = {}; obj = {   "1": "aa",   "2": "bb" };  obj.another = "valuehere"; obj["3"] = "cc"; 
like image 40
rfornal Avatar answered Sep 20 '22 20:09

rfornal