Can this assignment be made simpler by destructuring?

Viewed 1504

I'm still trying to learn all the way to destructure. I know enough to know that there might be a way to write this more concisely. Is there?

      this.props.setStateObjects({
        data:     data.reservation_data.data,
        included: data.reservation_data.included
      })

Edit:

As per @Sung M Kim's request below, this is the context:

    $.ajax({
    })
    .done( ( data ) => {
      this.props.setStateObjects({
        data:     data.reservation_data.data,
        included: data.reservation_data.included
      })
    })
2 Answers

You can apply destructuring to data to pluck out reservation_data, then pluck out data and included fields from reservation_data. Then you can set those in state with the shorthand object key value notation like so

const { reservation_data: { data: dataToSet, included } } = data

or less destructured

const { data: dataToSet, included } = data

then set it in state

this.props.setStateObjects({
  data: dataToSet,
  included
})

Using the spread operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

let pickedParameters = (({ data, included }) => ({ data, included }))(data.reservation_data);

this.props.setStateObjects({...pickedParameters});

Alternatively to get data and included you can use this format to avoid the function, still repetitive and ugly though:

let pickedParams = {};
({data: pickedParams.data, included: pickedParams.included} = data.reservation_data);
Related