27

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.

sandrooco
  • 8,016
  • 9
  • 48
  • 86

3 Answers3

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);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 2
    See [Is it possible to destructure instance/member variables in a JavaScript constructor? - Stack Overflow](https://stackoverflow.com/questions/38127416/is-it-possible-to-destructure-instance-member-variables-in-a-javascript-construc) for the reason why the parentheses is necessary. – user202729 Jan 18 '21 at 01:08
  • 1
    thanks.. i was wondering where the parenthesis was necessary.. – carinlynchin Feb 02 '21 at 23:44
12

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

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

let p = new Person();

console.log(p);
Linschlager
  • 1,539
  • 11
  • 18
pioro90
  • 684
  • 6
  • 14
  • 5
    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. – Stuart.Sklinar Nov 21 '17 at 12:22
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);
junvar
  • 11,151
  • 2
  • 30
  • 46