javascript - insert name and value pair - Stack Overflow

example :var data = { name : "John",age : 19}I want to add another pair inside the json objec

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" }

Share Improve this question edited Mar 20, 2012 at 12:14 Lightness Races in Orbit 386k77 gold badges666 silver badges1.1k bronze badges asked Mar 1, 2012 at 5:13 rjmcbrjmcb 3,7459 gold badges34 silver badges47 bronze badges 2
  • 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
Add a ment  | 

5 Answers 5

Reset to default 3

All 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

相关推荐

  • javascript - insert name and value pair - Stack Overflow

    example :var data = { name : "John",age : 19}I want to add another pair inside the json objec

    6天前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信