example :
var data = { name : "John",age : 19}
I want to add another pair inside the json object.
{gender : male}
so that it will become
data = { name : "John",age : 19,gender : "male" }
example :
var data = { name : "John",age : 19}
I want to add another pair inside the json object.
{gender : male}
so that it will become
data = { name : "John",age : 19,gender : "male" }
Yes, either:
data.gender = "male";
or
data['gender'] = "male";
(These are equivalent.)
If you are using jQuery (or one of many other libraries), you may have an "extend" function that is useful for that. It "merges" two Javascript objects. In jQuery:
$.extend(data, { gender: "male" });
This is nice because you can extend the JSON object with more than one value.
var data = { name : "John",age : 19};
var update = {gender : "male"};
function merge(target, source){
for(var prop in source){
target[prop] = source[prop];
}
return target;
}
var merged = merge(data, update);
This will add all properties in update
to data
. Using the returned value is optional. data
itself gets updated inside the function as it is object.
Or if you use jQuery
var merged = $.extend(data, update);
Using jQuery we can do a deep level merging
var update = {gender : "male", address:{house:"house1", street:"street1", pin:"pin1"}};
var merged = $.extend(true, data, update);
To achieve the same using plain javascript you have to modify and recursively call the function I have written above .
data.gender = "male"
More information here : Dynamically Add Variable Name Value Pairs to JSON Object