Skip to content

Latest commit

 

History

History
82 lines (60 loc) · 1.69 KB

prefer-object-from-entries.md

File metadata and controls

82 lines (60 loc) · 1.69 KB

Prefer using Object.fromEntries(…) to transform a list of key-value pairs into an object

💼 This rule is enabled in the ✅ recommended config.

🔧 This rule is automatically fixable by the --fix CLI option.

When transforming a list of key-value pairs into an object, Object.fromEntries(…) should be preferred.

This rule is fixable for simple cases.

Fail

const object = pairs.reduce(
	(object, [key, value]) => ({...object, [key]: value}),
	{}
);
const object = pairs.reduce(
	(object, [key, value]) => ({...object, [key]: value}),
	Object.create(null)
);
const object = pairs.reduce(
	(object, [key, value]) => Object.assign(object, {[key]: value}),
	{}
);
const object = _.fromPairs(pairs);

Pass

const object = Object.fromEntries(pairs);
const object = new Map(pairs);

Options

Type: object

functions

Type: string[]

You can also check custom functions that transforms pairs.

lodash.fromPairs() and _.fromPairs() are always checked.

Example:

{
	'unicorn/prefer-object-from-entries': [
		'error',
		{
			functions: [
				'getObjectFromKeyValue',
				'utils.fromPairs'
			]
		}
	]
}
// eslint unicorn/prefer-object-from-entries: ["error", {"functions": ["utils.fromPairs"]}]
const object = utils.fromPairs(pairs); // Fails