Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object assign with dynamic variable

I have this initialState in my Redux store:

const initialState = {
  isFetching : false,
  active     : {}
}

Where active is an object.

Now I have an action that should append or add a property to active’s data property, like so:

[DASHBOARD_TEMPLATE_DATA_RECEIVE]: (state, action) => {
    return Object.assign({}, state, {
      isFetching   : false,
      active       : Object.assign({}, active, {data[action.key]: action.data})
    })
}

As you can see, data[action.key] is not permitted. How do I do it?

like image 672
Joey Hipolito Avatar asked Jul 13 '16 15:07

Joey Hipolito


2 Answers

Try with this:

active: Object.assign({}, active, {
  data: Object.assign({}, data, {
    [action.key]: action.data
  })
})
like image 194
Iso Avatar answered Sep 30 '22 15:09

Iso


Build the object up first, making use of square bracket notation to use a string as a property name:

var data = {};
data[action.key] = action.data;

then use that newly created object:

[DASHBOARD_TEMPLATE_DATA_RECEIVE]: (state, action) => {
    return Object.assign({}, state, {
      isFetching   : false,
      active       : Object.assign({}, active, data)
    })
}
like image 36
Jamiec Avatar answered Sep 30 '22 15:09

Jamiec