繁体   English   中英

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

[英]Javascript objects: How do I make the value of a key be another key (not the key's value)?

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

 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键的VALUE:

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

当该值成为字符串时,所有属性都不会映射/起作用。

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

代替:

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

采用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM