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'});
0

2 Answers 2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Using Vuex objects in the states this is the recommended way if you want to keep the Vue.js reactivity.
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)

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.