Skip to main content

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


Here is my object literal:




var obj = {key1: value1, key2: value2};



How can I add {key3: value3} to the object?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. There are two ways to add new properties to an object:

    var obj = {
    key1: value1,
    key2: value2
    };


    Using dot notation:

    obj.key3 = "value3";


    Using square bracket notation:

    obj["key3"] = "value3";


    The first form is used when you know the name of the property. The second form is used when the name of the property is dynamically determined. Like in this example:

    var getProperty = function (propertyName) {
    return obj[propertyName];
    };

    getProperty("key1");
    getProperty("key2");
    getProperty("key3");




    A real JavaScript array can be constructed using either:

    The Array literal notation:

    var arr = [];


    The Array constructor notation:

    var arr = new Array();

    ReplyDelete
  2. You could use either of these (provided key3 is the acutal key you want to use)

    arr[ 'key3' ] = value3;


    or

    arr.key3 = value3;


    If key3 is a variable, then you should do:

    var key3 = 'a_key';
    var value3 = 3;
    arr[ key3 ] = value3;


    After this, requesting arr.a_key would return the value of value3, a literal 3.

    ReplyDelete
  3. arr.key3 = value3;


    because your arr is not really an array... It's a prototype object. The real array would be:

    var arr = [{key1: value1}, {key2: value2}];


    but it's still not right. It should actually be:

    var arr = [{key: key1, value: value1}, {key: key2, value: value2}];

    ReplyDelete
  4. Your example shows an Object, not an Array. In that case, the preferred way to add a field to an Object is to just assign to it, like so:

    arr.key3 = value3;

    ReplyDelete
  5. You can either add it this way:

    arr['key3'] = value3;


    or this way:

    arr.key3 = value3;


    The answers suggesting keying into the object with the variable key3 would only work if the value of key3 was 'key3'.

    ReplyDelete
  6. arr.push({key3: value3}); doesn't work :)

    ReplyDelete

Post a Comment

Popular posts from this blog

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?