LeBlaireau
LeBlaireau

Reputation: 17467

Setting an individual property of on an object

I have a class which sets the error an an object

one of the methods does this via a record method

  record(errors) {
        this.errors = errors;
      }

This accepts an object and sets the value. Typically I would get the errors like so

enter image description here

But what I am trying to do in put an individual error into the object

this.errors.record(this.errors.errors.username = {username: "this is my custom error"});

However the result was the whole object is overwritten

enter image description here

How do I change one value in this object?

Upvotes: 1

Views: 37

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073998

If your goal is to merge the object you're passing in with the object that's already there, you can use Object.assign to do that:

record(errors) {
    Object.assign(this.errors, errors);
}

That copies all of the "own" properties of errors to the pre-existing this.errors object.

If this.errors may not exist, you can add a guard and assignment:

record(errors) {
    this.errors = Object.assign(this.errors || {}, errors);
}

Object.assign returns its first argument. When this.errors doesn't exist (well, results in any falsy value), the new object {} will be used and returned, and then assigned to this.errors. But when this.errors exists (results in a truthy value), that one will be used and the assignment is a no-op.


Object.assign was added relatively recently, but is trivial to polyfill for older environments.

Upvotes: 1

Related Questions