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

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

    In case you have multiple anonymous Object literals inside an Object and want to add another Object containing key/value pairs, do this:

    Firebug' the Object:

    console.log(Comicbook);
    

    returns:

    [Object { name="Spiderman", value="11"}, Object { name="Marsipulami", value="18"}, Object { name="Garfield", value="2"}]

    Code:

    if (typeof Comicbook[3]=='undefined') {
        private_formArray[3] = new Object();
        private_formArray[3]["name"] = "Peanuts";
        private_formArray[3]["value"] = "12";
    }
    

    will add Object {name="Peanuts", value="12"} to the Comicbook Object

提交回复
热议问题