javascript - tslint:使用 reduce 构建对象时无对象突变
问题描述
我想以reduce
这种方式构建一个对象:
const result = [1, 2].reduce((partialResult, actualValue) => {
// define someKey and someValue
partialResult[someKey] = someValue;
return partialResult
}, {});
但是,我收到以下 tslint 错误:
Modifying properties of existing object not allowed. (no-object-mutation)
我该如何解决这个问题?
解决方案
要么修改代码,这样你就不会改变对象,这意味着你每次都必须复制它:
const result = [1, 2].reduce((partialResult, actualValue) => {
return {
...partialResult,
[someKey]: someValue,
}
}, {});
或禁用 lint 规则(如果您一般喜欢 lint 规则,则针对此特定行,或者如果您认为这是不必要的限制,则全局禁用)
推荐阅读
- c# - FSX 用户设计面板 L:var Get/Set
- mediawiki - GROUP BY like #ask query in semantic-mediawiki
- android - 带有孔的多边形在高缩放时行为不正确(消失)
- javascript - addEventlistener() 不执行函数
- c++ - 如何在 sql 查询中传递 C++ 变量
- firebase - 如何使用 GCP 对应用进行身份验证?
- default-value - 未连接 RealInput 的默认值
- json - Scala & Circe:带有可选字段的 JSON 编码
- python - send_task() 和 apply_async() 之间的区别
- html - 删除容器内某些元素的边距