π 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.
// β
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);Type: object
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);