Search code examples
javascriptlodashjavascript-objects

How to add dynamic key with value in existing Javascript object?


I have an existing javascript object.

let existingObject = {
    1: {
        'prop1': 'prop1 value',
        'prop2': 'prop2 value'
    },
    2: {
        'prop1': 'prop1 value',
        'prop2': 'prop2 value'
    },
    3: {
        'prop1': 'prop1 value',
        'prop2': 'prop2 value'
    }
}

I want to add a property to that existing object. My new key value is:

const key = 4;
const value = {
    'prop1': 'prop1 value',
    'prop2': 'prop2 value'
}

After appending the key and value, my new object should be,

const newObject = {
    1: {
        'prop1': 'prop1 value',
        'prop2': 'prop2 value'
    },
    2: {
        'prop1': 'prop1 value',
        'prop2': 'prop2 value'
    },
    3: {
        'prop1': 'prop1 value',
        'prop2': 'prop2 value'
    },
    4: {
        'prop1': 'prop1 value',
        'prop2': 'prop2 value'
    }
}

Here the key is a dynamic value. Whenever I try to append this key-value, the key is becoming the variable name.

How can I solve this issue?

NB: For creating the existing object I am using lodash.


Solution

  • You can do this with Object.assign() and using Computed Property names (example {[key]: value}):

    let existingObject = {
        1: {'prop1': 'prop1 value', 'prop2': 'prop2 value'},
        2: {'prop1': 'prop1 value', 'prop2': 'prop2 value'},
        3: {'prop1': 'prop1 value', 'prop2': 'prop2 value'}
    }
    
    const key = 4;
    const value = {'prop1': 'prop1 value', 'prop2': 'prop2 value'}
    
    Object.assign(existingObject, {[key]: value});
    console.log(existingObject);
    .as-console {background-color:black !important; color:lime;}
    .as-console-wrapper {max-height:100% !important; top:0;}

    But, as others have commented to you, this is easy as just:

    existingObject[key] = value;