Skip to main content

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

You can add key/value pair to a javascript object using dot notation and square brackets notation.

  • Add key/value pair to javascript object using dot notation

    const obj = {
        key1: 'value1',
        key2: 'value2'
    };
    obj.key3 = "value3";
    console.log(obj);

    Output:

    { key1: 'value1', key2: 'value2', key3: 'value3' }

    You have to use dot notation in between object and new key (object.key) and assign value to key using assignment operator (=) in javascript to add a new key and value pair to an existing javascript object. 

  • Add key/value pair to javascript object usign square bracket notation

    const obj = {
        key1: 'value1',
        key2: 'value2'
    };
    obj["key3"] = "value3";
    console.log(obj);

    Output:

    { key1: 'value1', key2: 'value2', key3: 'value3' }

    You can add a new key/value pair to object in javascript using square ([]) notation. It will helps you to add a new values (key/value) to an existing object in javascript.

  • Back to code snippet queries related javascript