Search code examples
javascriptdestructuringecmascript-2016

destructuring ecmascript es7


Is there a way to simplify the following code?

let { page_size, current_page } = paging;

this.p_start = page_size * current_page;
this.p_current = current_page;
this.p_dg_current = this.p_current + 1;
this.p_size = page_size;

paging is an object and has properties page_size and current_page.

Is there a destructing way to assign the paging.page_size and paging.current_page directly to this.p_size and this.p_current?

  let { this.p_size = page_size, this.p_current = current_page } = paging;

  this.p_start = page_size * current_page;
  this.p_dg_current = this.p_current + 1;

Solution

  • The syntax for destructuring is { propertyName: targetExpression = default }. You have the right idea though (and you need to omit the let, as you're not declaring variables):

    ({ page_size: this.p_size, current_page: this.p_current } = paging);
    
    this.p_start = this.p_size * this.p_current;
    this.p_dg_current = this.p_current + 1;