admin管理员组

文章数量:1291038

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?

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?

Share Improve this question edited Jul 13, 2016 at 15:51 Sebastian Simon 19.5k8 gold badges61 silver badges84 bronze badges asked Jul 13, 2016 at 15:48 Joey HipolitoJoey Hipolito 3,16611 gold badges46 silver badges84 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

Try with this:

active: Object.assign({}, active, {
  data: Object.assign({}, data, {
    [action.key]: action.data
  })
})

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)
    })
}

I would guess a puted property name might work.

Untested:

active: Object.assign({}, active, {[data[action.key]]: action.data})

本文标签: javascriptObject assign with dynamic variableStack Overflow