Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Destructuring assignment with `this`

Tags:

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.

like image 651
sandrooco Avatar asked Nov 21 '17 10:11

sandrooco


People also ask

What is Destructured assignment in JavaScript?

Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables.

What is Destructuring ES6?

The destructuring assignment is a cool feature that came along with ES6. Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables.

What are default values in Destructuring assignment in JavaScript?

Each destructured property can have a default value. The default value is used when the property is not present, or has value undefined . It is not used if the property has value null . The default value can be any expression.

How do you Destructure an array of elements?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element. const [var1, var2, ...]


2 Answers

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);
like image 178
Ori Drori Avatar answered Oct 17 '22 15:10

Ori Drori


function Person() {    this.obj = {      firstName: 'Dav',      lastName: 'P'    };      ({firstName: this.firstName, lastName: this.lastName} = this.obj);  }    let p = new Person();    console.log(p);
like image 20
pioro90 Avatar answered Oct 17 '22 15:10

pioro90