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

前端 未结 24 3326
情歌与酒
情歌与酒 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:41

    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/

提交回复
热议问题