29

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'});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
agreis1
  • 1,021
  • 5
  • 13
  • 17

2 Answers2

56

Object.assign is nice for this:

var myObject = {
    label: 'foo',
    name: 'bar',
    id: 12
}
Object.assign(myObject, {label: 'Test', name: 'Barbar'})
console.log(myObject)
Mark
  • 90,562
  • 7
  • 108
  • 148
  • 1
    Using Vuex objects in the states this is the recommended way if you want to keep the Vue.js reactivity. – hermeslm Apr 11 '20 at 23:42
17

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)
CRice
  • 29,968
  • 4
  • 57
  • 70
  • 19
    Unlike `Object.assign`, this doesn’t actually “update” the object, it makes a whole new one, so if `myObject` is aliased the original version will remain visible there unchanged. That may or may not be ok. – Michael Homer Aug 16 '18 at 04:25