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

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

    supported by most of browsers, and it checks if object key available or not you want to add, if available it overides existing key value and it not available it add key with value

    example 1

    let my_object = {};
    
    // now i want to add something in it  
    
    my_object.red = "this is red color";
    
    // { red : "this is red color"}
    

    example 2

    let my_object = { inside_object : { car : "maruti" }}
    
    // now i want to add something inside object of my object 
    
    my_object.inside_object.plane = "JetKing";
    
    // { inside_object : { car : "maruti" , plane : "JetKing"} }
    

    example 3

    let my_object = { inside_object : { name : "abhishek" }}
    
    // now i want to add something inside object with new keys birth , gender 
    
    my_object.inside_object.birth = "8 Aug";
    my_object.inside_object.gender = "Male";
    
    
        // { inside_object : 
    //             { name : "abhishek",
    //               birth : "8 Aug",
    //               gender : "Male" 
    //            }   
    //       }
    

提交回复
热议问题