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

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

    Since its a question of the past but the problem of present. Would suggest one more solution: Just pass the key and values to the function and you will get a map object.

    var map = {};
    function addValueToMap(key, value) {
    map[key] = map[key] || [];
    map[key].push(value);
    }
    

提交回复
热议问题