0

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 = ?

5
  • 2
    So what went wrong with Object.assign? It will update this if you pass that as first argument. No need to assign anything more. Commented Nov 11, 2018 at 21:08
  • but i would have to assign it to something right? like this = Object.assign(this, o) but that's a no-go Commented Nov 11, 2018 at 21:24
  • You need to create a new Car() first Commented Nov 11, 2018 at 21:35
  • @trincot Ah, i see. looking at the docs, i didn't realize it copies to the first parameter which is the target. I thought it had to return something which you would then save to a var. convert that to an answer. :) Commented Nov 11, 2018 at 21:35
  • OK, I have done so. Commented Nov 11, 2018 at 21:42

3 Answers 3

1

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"

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

Comments

0

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);

Comments

0
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

1 Comment

I just wanted it to be in a method, to keep it clean and so i can tie other functionality to it whenever there is an update, i updated my question to show what else I would like to tie in. to give a better idea of what i'm trying to accomplish

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.