This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
                            
                                (18个回答)
                            
                    
                2年前关闭。
        

    

我有一个动作“ set-style”被发送到一个reducer,在那我更改了对象数组(称为图层)中按键指定对象的样式对象。

困难在于-'filterName'用于接收需要更改的属性名称。
如果我使用另一个属性名称,它的行为确实正确,但是'filterName'变量不能用作键。

export const set_stl = (val,filterName,chosenLayerId,chosenLayerIdx=0,layers) => {
const specLayer = layers[chosenLayerIdx];
const assignedSpecLayer = Object.assign({}, specLayer, {
    stl: {
        ...specLayer.stl,
        filterName: val
    }
});
const newLayers = layers;
    newLayers[chosenLayerIdx] = assignedSpecLayer;
return dispatch => {
    dispatch({
        type: SET_STL,
        payload: newLayers,
    })
}


};

最佳答案

您需要使用[]来使用filterName的值。

stl: {
    ...specLayer.stl,
    [filterName]: val
}

09-30 16:28