[英]Why does accessing an object literal with bracket notation and a key containing spaces result in undefined?
[英]How to not set a key in object literal notation if the value of the key is undefined
我正在使用Redux创建一个RPG角色生成器。 在我的减速器中,我希望能够修改齿轮并跟踪这些修改。 修改可以具有等级,但不一定必须具有等级。
因此,如果等级未定义,我宁愿不记录下来。 那么,如果值未定义,有没有办法不以对象文字表示法添加键?
gearName将是要修改的齿轮的字符串。
mod是一个包含有关mod的属性的对象,例如+ rating耐火等级或其他。
等级是代表修改值的数字。
const purchaseGear = (state, action) => {
const { gearName, mod, rating } = action.parameter;
switch (action.type) {
case MOD_GEAR:
return {
...state,
[gearName]: {
...state[gearName],
mods: {
...state[gearName].mods,
[mod.name]: {
...mod,
rating
}
},
cost: mod.cost * (rating || 1)
}
}
}
2ality.com上的Axel Rauschmayer提出了以下模式:
const cond = false;
const obj = {
...(cond ? {a: 1} : {}),
b: 2,
};
// {b: 2}
所以在你的情况下
...(rating !== undefined ? {rating: rating} : {})
请记住,只有当引擎已经支持Object rest / spread-proposal时 ,此模式才有效。 它可以在Chrome v58中使用,但我尚未在其他平台上进行过测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.