Skip to content

Latest commit

Β 

History

History
76 lines (55 loc) Β· 1.78 KB

File metadata and controls

76 lines (55 loc) Β· 1.78 KB

prefer-object-from-entries

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

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ”§ 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. no-array-reduce is a related but more generic rule.

This rule is fixable for simple cases.

Examples

// ❌
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);

// βœ…
const object = Object.fromEntries(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);