0

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...

M Xiao
  • 553
  • 1
  • 7
  • 14

1 Answers1

1

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
Anand Undavia
  • 3,493
  • 5
  • 19
  • 33
  • Thanks! I'll mark this as correct, but what would you do it you had to add multiple different tableTypes (e.g. this.props.funTable and this.props.notFunTable), can you chain the ternary operation all the way down? – M Xiao Jul 31 '18 at 19:39
  • 1
    Yes, you can chain the ternary operator all the way down or just use `if-elseif-else` ladder – Anand Undavia Jul 31 '18 at 19:41
  • However, a better approach would be to have two props; one that holds the data, and another that holds the type of data. For example, `props.tableData` and `props.tableDataType`. Because the shape of `props.tableData` is same across all types, you can just use. And you can use `props.tableDataType` when rendering conditionally – Anand Undavia Jul 31 '18 at 19:44