unicorn/prefer-object-from-entries 风格
它的作用
鼓励在将键值对数组转换为对象时使用 Object.fromEntries。
为什么这是不好的?
使用 reduce 或 forEach 手动构造对象来处理键值对更加冗长、容易出错,且更难理解。Object.fromEntries 方法更加清晰、更具声明性,并专为此用途而设计。
示例
此规则的 错误 代码示例:
js
const result = pairs.reduce((obj, [key, value]) => {
obj[key] = value;
return obj;
}, {});
const result = {};
pairs.forEach(([key, value]) => {
result[key] = value;
});此规则的 正确 代码示例:
js
const result = Object.fromEntries(pairs);配置
此规则接受一个配置对象,包含以下属性:
functions
type: string[]
默认值: ["_.fromPairs", "lodash.fromPairs"]
额外指定与 Object.fromEntries 等效的函数。
如何使用
通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"unicorn/prefer-object-from-entries": "error"
}
}bash
oxlint --deny unicorn/prefer-object-from-entries