Search code examples
javascriptlodash

How do you add new or update existing object properties using lodash only or plain javascript?


Say you have defined an object like:

let myObject = {};

And you were going to add unknown properties that may or may not already exist. To where myObject would look more like:

{
    foo: {
        prop: 'SOME PROP NAME',
        val:  'SOME VAL'
    },
    bar: {
        prop: 'SOME PROP NAME',
        val:  'SOME VAL'
    },
    baz: {
        prop: 'SOME PROP NAME',
        val:  'SOME VAL'
    }
}

Keep in mind that foo.prop and foo.val may be set at different times. With props and vals set at the same time I'd probably just use _.assign() and maybe it's as simple as that with an extra layer added.

Assume there is a function like:

updateMyObject(e, attr, key) {
    myObject[attr][key] = e.target.value;
}

Which obviously doesn't work

I'm looking for a function that would work.


Solution

  • Before adding a new key and value, you can check if myObject contains attr, otherwise create it.

    updateMyObject(e, attr, key) {
      if(!(attr in myObject))
        myObject[attr] = {};
      myObject[attr][key] = e.target.value;
    }