-2

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.

Shams Nahid
  • 6,239
  • 8
  • 28
  • 39
  • 1
    `existingObject[key] = value` – Paul Feb 10 '19 at 05:26
  • 1
    Possible duplicate of [How can I add a key/value pair to a JavaScript object?](https://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object) and [JavaScript set object key by variable](https://stackoverflow.com/questions/11508463) – adiga Feb 10 '19 at 05:26
  • 1
    If you want consecutive numeric keys, why don't you use an array? – adiga Feb 10 '19 at 05:28
  • You haven't even shown any of the code attempts here. – charlietfl Feb 10 '19 at 05:39

1 Answers1

6

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;
Shidersz
  • 16,846
  • 2
  • 23
  • 48