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

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

    Best way to achieve same is stated below:

    function getKey(key) {
      return `${key}`;
    }
    
    var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};
    
    //console.log(obj);
    
    0 讨论(0)
  • 2020-11-21 07:35

    You can create a class with the answer of @Ionuț G. Stan

    function obj(){
        obj=new Object();
        this.add=function(key,value){
            obj[""+key+""]=value;
        }
        this.obj=obj
    }
    

    Creating a new object with the last class:

    my_obj=new obj();
    my_obj.add('key1', 'value1');
    my_obj.add('key2', 'value2');
    my_obj.add('key3','value3');
    

    Printing the object

    console.log(my_obj.obj) // Return {key1: "value1", key2: "value2", key3: "value3"} 
    

    Printing a Key

    console.log(my_obj.obj["key3"]) //Return value3
    

    I'm newbie in javascript, comments are welcome. Works for me.

    0 讨论(0)
  • 2020-11-21 07:35

    Two most used ways already mentioned in most answers

    obj.key3 = "value3";
    
    obj["key3"] = "value3";
    

    One more way to define a property is using Object.defineProperty()

    Object.defineProperty(obj, 'key3', {
      value: "value3",       // undefined by default
      enumerable: true,      // false by default
      configurable: true,    // false by default
      writable: true         // false by default
    });
    

    This method is useful when you want to have more control while defining property. Property defined can be set as enumerable, configurable and writable by user.

    0 讨论(0)
  • 2020-11-21 07:39
    var employees = []; 
    employees.push({id:100,name:'Yashwant',age:30});
    employees.push({id:200,name:'Mahesh',age:35});
    
    0 讨论(0)
  • 2020-11-21 07:39

    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));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p id="ini">Initial: </p>
    <p id="ext">Extended: </p>

    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));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p id="ini">Initial: </p>
    <p id="ext">Extended: </p>

    0 讨论(0)
  • 2020-11-21 07:39

    According to Property Accessors defined in ECMA-262(http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf, P67), there are two ways you can do to add properties to a exists object. All these two way, the Javascript engine will treat them the same.

    The first way is to use dot notation:

    obj.key3 = value3;
    

    But this way, you should use a IdentifierName after dot notation.

    The second way is to use bracket notation:

    obj["key3"] = value3;
    

    and another form:

    var key3 = "key3";
    obj[key3] = value3;
    

    This way, you could use a Expression (include IdentifierName) in the bracket notation.

    0 讨论(0)
提交回复
热议问题