M Xiao
M Xiao

Reputation: 663

Setting the values of previously initialized variables using object destructuring syntax

my situation is that I have a number of variables I want to set - however, their values are conditional on another variable. So here's what I mean

var {
      columns,
      rows,
      tableColumnExtensions,
      sorting,
      editingRowIds,
      addedRows,
      rowChanges,
      currentPage,
      deletingRows,
      pageSize,
      pageSizes,
      columnOrder,
    } = this.props.apiurlsTable

    if (this.props.tableType==="dependencies") {
      var {
        columns,
        rows,
        tableColumnExtensions,
        sorting,
        editingRowIds,
        addedRows,
        rowChanges,
        currentPage,
        deletingRows,
        pageSize,
        pageSizes,
        columnOrder,
      } = this.props.dependenciesTable
    }

I use the variables declared later, so declaring them always within a conditional would be no good because they wouldn't be visible to remaining scope of the function. The code above actually does work, but gives a 'variable is already defined, no-redeclare' warning. I like using the Object destructuring syntax and would prefer not to have to separate each variable on to its own line (like columns = this.props.dependenciesTable.column) I was wondering if there is a way to conditionally set variables in JavaScript?

Or is there another approach that would work...

Upvotes: 0

Views: 31

Answers (1)

Anand Undavia
Anand Undavia

Reputation: 3543

Do this:

var objectToDestructureFrom =
    this.props.tableType === "dependencies" ? this.props.dependenciesTable : this.props.apiurlsTable;

var {
    columns,
    rows,
    tableColumnExtensions,
    sorting,
    editingRowIds,
    addedRows,
    rowChanges,
    currentPage,
    deletingRows,
    pageSize,
    pageSizes,
    columnOrder,
} = objectToDestructureFrom

Upvotes: 1

Related Questions