Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add field key3
with value3
to the ob
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: