ES6 Destructuring assignment with `this`
Asked Answered
S

3

28

The code below works. Is there a way that is more convenient, if possible even a one-liner?

const { nextUrl, posts } = await postService.getCommunityPosts(6);
this.communityPosts = posts;
this.nextUrl = nextUrl;

I know about giving destructured properties aliases but I don't think that helps in this case. MDN doesn't say anything about that case.

Scuba answered 21/11, 2017 at 10:38 Comment(0)
V
36

You can assign to the properties of an existing object by giving aliases and encapsulating the assignment in parentheses (await codepen).

const demo = { nextUrl: 'nextUrl', posts: 'posts' };

const target = {}; // replace target with this

({ nextUrl: target.nextUrl, posts: target.communityPosts } = demo);

console.log(target);
Vimineous answered 21/11, 2017 at 10:41 Comment(2)
See Is it possible to destructure instance/member variables in a JavaScript constructor? - Stack Overflow for the reason why the parentheses is necessary.Around
thanks.. i was wondering where the parenthesis was necessary..Component
I
12

function Person() {
  this.obj = {
    firstName: 'Dav',
    lastName: 'P'
  };

  ({firstName: this.firstName, lastName: this.lastName} = this.obj);
}

let p = new Person();

console.log(p);
Inviolable answered 21/11, 2017 at 10:51 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Spontaneous
I
2

An alternative that doesn't require duplicate property keys that ({key1: this.key1, key2: this.key2} = ... does is to use Object.assign().

class X {
  constructor(properties) {
    ({...this} = properties); // Invalid destructuring assignment target
  }
}

x = new X({a: 3});
console.log(x);

class X {
  constructor(properties) {
    Object.assign(this, properties);
  }
}

x = new X({a: 3});
console.log(x);
Immobile answered 9/6, 2021 at 18:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.