Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple values of object in JavaScript [duplicate]

Tags:

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'}); 
like image 449
agreis1 Avatar asked Aug 16 '18 00:08

agreis1


2 Answers

Object.assign is nice for this:

var myObject = {      label: 'foo',      name: 'bar',      id: 12  }  Object.assign(myObject, {label: 'Test', name: 'Barbar'})  console.log(myObject)
like image 77
Mark Avatar answered Sep 18 '22 18:09

Mark


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)
like image 37
CRice Avatar answered Sep 17 '22 18:09

CRice