example :
var data = { name : "John",age : 19}
I want to add another pair inside the json object.
{gender : male}
so that it will bee
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 bee
data = { name : "John",age : 19,gender : "male" }
- 2 <pedantic>It isn't really a "JSON object" you have here, but a JavaScript one</pedantic>. JSON is a text format, and BTW the key names must be double quoted. – Ray Toal Commented Mar 1, 2012 at 5:17
- @RayToal: Not "pedantic" at all. – Lightness Races in Orbit Commented Mar 20, 2012 at 12:14
5 Answers
Reset to default 3All you need is
data.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 .
Try this:
var data = { name : "John",age : 19};
data.gender = "male";
data.gender = "male"
More information here : Dynamically Add Variable Name Value Pairs to JSON Object
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744413365a4572993.html
评论列表(0条)