[英]Javascript objects: How do I make the value of a key be another key (not the key's value)?
Is there a way to programmatically set the value of a key to another key? 有没有办法以编程方式将一个键的值设置为另一个键? eg 例如
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; }
The goal is for this to return an object where each key, value pair is like so: 目的是返回一个对象,其中每个键,值对如下所示:
namespace: state.city.namespace
What I am actually getting is the VALUE of the state.city.namespace key: 我实际上得到的是state.city.namespace键的VALUE:
namespace: 'DIskieisSi98s8sjw'.
Thanks in advance for your help! 在此先感谢您的帮助!
EDIT -- ADDING ADDITIONAL CONTEXT 编辑-添加其他上下文
@mem035 I probably should have added this context. @ mem035我可能应该添加此上下文。 I am trying create a function that will enable me to stop having to type out the mapStateToProps for Redux. 我正在尝试创建一个函数,使我不必再为Redux输入mapStateToProps了。 For the above example, here is the 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 }; };
When the value becomes a string none of the properties are mapping/working. 当该值成为字符串时,所有属性都不会映射/起作用。
Just stringify your result instead of again accessing the object. 只需对结果进行字符串化处理,而不是再次访问该对象。
Instead of: 代替:
stateObject[key] = state[reducer][key];
Use: 采用:
stateObject[key] = `state.${reducer}.${key}`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.