WillKre
WillKre

Reputation: 6158

Use a variable as an object key in reducer

I'm having trouble constructing an object. I've got a string (called "SKU" for this example) and it's coming through action as action.name.

I have everything available in the reducer function but I need to change the hardcoded SKU to action.name, but obviously that's not possible in JS. I've tried action.name, action['name'] and other variations and I'm stuck.

What is the work around? Any help appreciated! Thanks.

Here's some code so you can see what's going on:

function that fires when date changes...

handleChange(date) {
  this.props.addDate(date, this.props.dashboardName);
}

mapDispatch which is connected at the bottom of the component export...

const mapDispatchToProps = dispatch => {
  return {
    addDate: (date, name) => dispatch({
      type: 'ACTION_DASHBOARD_ADD_DATE',
      date,
      name
    })
  };
};

action creator...

export function DashboardDate() {
  return {
    type: ACTION_DASHBOARD_ADD_DATE
  };
}

case in the switch of the reducer...

case ACTION_DASHBOARD_ADD_DATE: {
      var filter = {};
      filter[action.name] = action.date;
      return {
        ...state,
        dashboard: {
          ...state.dashboard,
          // Below SKU needs to be the value of action.name
          SKU: {
            // Below too, action.name
            ...state.dashboard.SKU,
            filter
          }
        }
      };
    }

Upvotes: 7

Views: 5262

Answers (2)

Aron
Aron

Reputation: 9248

I'm not 100% sure where in your code you want to have the sku appear, but you can create an object with a computed property name like this:

const obj = {
    [action.name]: action.payload
};

console.log(obj); // { "sku": "abcd" }

Computed property names are an ES2015 (ES6) feature.

Upvotes: 17

Vincent
Vincent

Reputation: 316

Use [action.name] (syntax for computed key)

case ACTION_DASHBOARD_ADD_DATE: {
  var filter = {};
  filter[action.name] = action.date;
  return {
    ...state,
    dashboard: {
      ...state.dashboard,
      [action.name]: {
        ...state.dashboard.SKU,
        filter
      }
    }
  };
}

Upvotes: 6

Related Questions