How can I add a key/value pair to a JavaScript object?

前端 未结 24 3343
情歌与酒
情歌与酒 2020-11-21 07:01

Here is my object literal:

var obj = {key1: value1, key2: value2};

How can I add field key3 with value3 to the ob

24条回答
  •  悲哀的现实
    2020-11-21 07:39

    Either obj['key3'] = value3 or obj.key3 = value3 will add the new pair to the obj.

    However, I know jQuery was not mentioned, but if you're using it, you can add the object through $.extend(obj,{key3: 'value3'}). E.g.:

    var obj = {key1: 'value1', key2: 'value2'};
    $('#ini').append(JSON.stringify(obj));
    
    $.extend(obj,{key3: 'value3'});
    
    $('#ext').append(JSON.stringify(obj));
    
    

    Initial:

    Extended:

    jQuery.extend(target[,object1][,objectN]) merges the contents of two or more objects together into the first object.

    And it also allows recursive adds/modifications with $.extend(true,object1,object2);:

    var object1 = {
      apple: 0,
      banana: { weight: 52, price: 100 },
      cherry: 97
    };
    var object2 = {
      banana: { price: 200 },
      durian: 100
    };
    $("#ini").append(JSON.stringify(object1));    
    
    $.extend( true, object1, object2 );
     
    $("#ext").append(JSON.stringify(object1));
    
    

    Initial:

    Extended:

提交回复
热议问题