gpt4 book ai didi

JavaScript 对象 : How do I make the value of a key be another key (not the key's value)?

转载 作者:行者123 更新时间:2023-12-03 00:56:11 24 4
gpt4 key购买 nike

有没有办法以编程方式将一个键的值设置为另一个键?例如

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。对于上面的例子,这是 map :

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

当值变成字符串时,所有属性都不会映射/工作。

最佳答案

只需将结果字符串化,而不是再次访问对象。

而不是:

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

用途:

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

关于JavaScript 对象 : How do I make the value of a key be another key (not the key's value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52826819/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com