Search code examples
javascriptecmascript-6constantslet

how to pass argument to const object variable


Given

 onColumnResize(column) {

    const columnsWidth = {
        columnsWidth: {
            column: width + 'px'
        },
        detail: this.details
    };

}

how to pass argument column to the object columnsWidth variable? for example: if argument column = 'name', would like to pass 'name' to column and output the following (depending on the argument of the function):

onColumnResize(column) {
 const columnsWidth = {
        columnsWidth: {
            'name': width + 'px'
        },
        detail: this.details
    };
}

my attempt: `

 onColumnResize(column) {
      const columnsWidth = {};
      columnsWidth[column] = width+'px';
      columnsWidth.detail = this.details;
  }`

is there other method beside the above?


Solution

  • Change column to [column] in your first code block:

    onColumnResize(column) {
      const columnsWidth = {
        columnsWidth: {
          [column]: width + 'px'
        },
        detail: this.details
      };
    
      // ...
    }
    

    This is called a computed property name, and it's part of ES2015, not ES2016.