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.
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.
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.
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.
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, ...]
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);
function Person() { this.obj = { firstName: 'Dav', lastName: 'P' }; ({firstName: this.firstName, lastName: this.lastName} = this.obj); } let p = new Person(); console.log(p);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With