Javascript对象:如何使键的值成为另一个键(而不是键的值)?

时间:2018-10-16 01:42:51

标签: javascript object

是否可以通过编程方式将一个键的值设置为另一个键?例如

export function getObjectForMapStateToProps(state, reducer) {
    let stateObject = {};
    for (let key in state[reducer]) {
        if (state[reducer].hasOwnProperty(key)) {
            stateObject[key] = state[reducer][key];
        }
    }
    return stateObject;
}

目标是返回一个其中每个键,值对如下的对象:

namespace: state.city.namespace

我实际上得到的是state.city.namespace键的值:

namespace: 'DIskieisSi98s8sjw'.

在此先感谢您的帮助!

编辑-添加其他上下文

@ mem035我可能应该添加此上下文。我正在尝试创建一个函数,使我不必再为Redux输入mapStateToProps了。对于上面的示例,这是地图:

const mapStateToProps = state => {
    console.log(getObjectForMapStateToProps(state, 'city'));
    return {
        namespace: state.city.namespace,
        componentId: state.city.componentId,
        items: state.city.items,
        defaultValue: state.city.defaultValue,
        selectItem: state.city.selectItem,
        allowAdd: state.city.allowAdd,
        validationRegEx: state.city.validationRegEx,
        regExDescription: state.city.regExDescription,
        hasForeignKey: state.city.hasForeignKey,
        foreignKeyModel: state.city.foreignKeyModel,
        foreignKeyValue: state.city.foreignKeyValue,
        errorMessages: state.city.errorMessages,
        isError: state.city.isError,
        isLoading: state.city.isLoading,
        apiRoute: state.city.apiRoute
    };
};

当该值成为字符串时,所有属性均未在映射/工作。

1 个答案:

答案 0 :(得分:1)

只需对结果进行字符串化处理,而不是再次访问该对象。

代替:

stateObject[key] = state[reducer][key];

使用:

stateObject[key] = `state.${reducer}.${key}`;