24

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
  • 6,584
  • 7
  • 39
  • 78

3 Answers3

32

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
  • 166,183
  • 27
  • 198
  • 186
  • 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
9

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,281
  • 11
  • 18
pioro90
  • 624
  • 5
  • 13
  • 4
    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
1

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
  • 10,160
  • 2
  • 23
  • 40