Skip to content

unicorn/prefer-object-from-entries Style ​

🚧 An auto-fix is still under development.

What it does ​

Encourages using Object.fromEntries when converting an array of key-value pairs into an object.

Why is this bad? ​

Manually constructing objects from key-value pairs using reduce or forEach is more verbose, error-prone, and harder to understand. The Object.fromEntries method is clearer, more declarative, and built for exactly this purpose.

Examples ​

Examples of incorrect code for this rule:

js
const result = pairs.reduce((obj, [key, value]) => {
  obj[key] = value;
  return obj;
}, {});

const result = {};
pairs.forEach(([key, value]) => {
  result[key] = value;
});

Examples of correct code for this rule:

js
const result = Object.fromEntries(pairs);

How to use ​

To enable this rule in the CLI or using the config file, you can use:

bash
oxlint --deny unicorn/prefer-object-from-entries
json
{
  "rules": {
    "unicorn/prefer-object-from-entries": "error"
  }
}

References ​

Released under the MIT License.