💼 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.
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);
const object = new Map(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); // Fails