Here is my object literal:
var obj = {key1: value1, key2: value2};
How can I add field key3
with value3
to the ob
I know there is already an accepted answer for this but I thought I'd document my idea somewhere. Please [people] feel free to poke holes in this idea, as I'm not sure if it is the best solution... but I just put this together a few minutes ago:
Object.prototype.push = function( key, value ){
this[ key ] = value;
return this;
}
You would utilize it in this way:
var obj = {key1: value1, key2: value2};
obj.push( "key3", "value3" );
Since, the prototype function is returning this
you can continue to chain .push
's to the end of your obj
variable: obj.push(...).push(...).push(...);
Another feature is that you can pass an array or another object as the value in the push function arguments. See my fiddle for a working example: http://jsfiddle.net/7tEme/