-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.

4
  • 1
    existingObject[key] = value Commented Feb 10, 2019 at 5:26
  • 1
    Possible duplicate of How can I add a key/value pair to a JavaScript object? and JavaScript set object key by variable Commented Feb 10, 2019 at 5:26
  • 1
    If you want consecutive numeric keys, why don't you use an array? Commented Feb 10, 2019 at 5:28
  • You haven't even shown any of the code attempts here. Commented Feb 10, 2019 at 5:39

1 Answer 1

8

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.