Given an object
var myObject = { label: 'foo', name: 'bar', id: 12 },
If I wanted to change multiple values, I would do the following:
myObject.label = "bar"; myObject.name = "foo";
When updating large sets of data, it makes the code quite blocky. Is there a way to do this in a more concise manner?
Like:
myObject.({label: 'foo'}, {name: 'bar'});
Object.assign
is nice for this:
var myObject = { label: 'foo', name: 'bar', id: 12 } Object.assign(myObject, {label: 'Test', name: 'Barbar'}) console.log(myObject)
In addition to Object.assign
, you can also use the object spread operator:
var myObject = { label: 'foo', name: 'bar', id: 12 }; myObject = {...myObject, label: 'baz', name: 'qux'}; console.log(myObject); // Or, if your update is contained in its own object: var myUpdate = { label: 'something', name: 'else' } myObject = {...myObject, ...myUpdate} console.log(myObject)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With