Olgo
Olgo

Reputation: 35

How would I set up a method to update passed properties of JavaScript object?

I'm looking to create a method for an object to update only the properties that are passed.

for example

function Car () {
  this.color = 'yellow'
  this.brand = 'bmw'
  this.key = 0

  this.update = function (o) {
    this.key++
    // maybe Object.assign(this, o) somehow ??
  }
}

If I do Car.update({color:'red'}) I want to update the object but not overwrite the brand. I want to use something like Object.assign(this, o) but not sure how to assign it. Do I need to create a prototype? Car.prototype.update = ?

Upvotes: 0

Views: 836

Answers (3)

trincot
trincot

Reputation: 350270

Object.assign mutates the first argument, so there is no need to assign the result of Object.assign() to something.

Object.assign(this, o);

...will work fine.

function Car () {
  this.color = 'yellow'
  this.brand = 'bmw'
  this.key = 0

  this.update = function (o) {
    this.key++
    Object.assign(this, o);
  }
}

var car = new Car();
car.update({color: 'red'});
console.log(car);

Upvotes: 0

M. L.
M. L.

Reputation: 46

The idea you suggested in your OP works fine.

function Car () {
  this.color = 'yellow';
  this.brand = 'bmw';
  this.key = 0;

  this.update = function (o) {
	Object.assign(this, o);
  }
}

a = new Car();
a.update({color: "red"});
console.log(a.color + " - " + a.brand + " - " + a.key);
// returns "red - bmw - 0"

Upvotes: 1

const object1 = {
color : 'red'
};

const obj2 = Object.assign({color: 'blue', d: 5}, object1);
console.log(obj2.color); // red

Object.assign() method -> copy the values of all enumerable own properties. Finally It will return the target object

Upvotes: 0

Related Questions