|
| 1 | +# Prefer using `Object.fromEntries(…)` to transform a list of key-value pairs into an object |
| 2 | + |
| 3 | +When transforming a list of key-value pairs into an object, [`Object.fromEntries(…)`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) should be preferred. |
| 4 | + |
| 5 | +This rule is fixable for simple cases. |
| 6 | + |
| 7 | +## Fail |
| 8 | + |
| 9 | +```js |
| 10 | +const object = pairs.reduce( |
| 11 | + (object, [key, value]) => ({...object, [key]: value}), |
| 12 | + {} |
| 13 | +); |
| 14 | +``` |
| 15 | + |
| 16 | +```js |
| 17 | +const object = pairs.reduce( |
| 18 | + (object, [key, value]) => ({...object, [key]: value}), |
| 19 | + Object.create(null) |
| 20 | +); |
| 21 | +``` |
| 22 | + |
| 23 | +```js |
| 24 | +const object = pairs.reduce( |
| 25 | + (object, [key, value]) => Object.assign(object, {[key]: value}), |
| 26 | + {} |
| 27 | +); |
| 28 | +``` |
| 29 | + |
| 30 | +```js |
| 31 | +const object = pairs.reduce(addPairToObject, {}); |
| 32 | +``` |
| 33 | + |
| 34 | +```js |
| 35 | +const object = _.fromPairs(pairs); |
| 36 | +``` |
| 37 | + |
| 38 | +## Pass |
| 39 | + |
| 40 | +```js |
| 41 | +const object = Object.fromEntries(pairs); |
| 42 | +``` |
| 43 | + |
| 44 | +```js |
| 45 | +const object = new Map(pairs); |
| 46 | +``` |
| 47 | + |
| 48 | +## Options |
| 49 | + |
| 50 | +Type: `object` |
| 51 | + |
| 52 | +### functions |
| 53 | + |
| 54 | +Type: `string[]` |
| 55 | + |
| 56 | +You can also check custom functions that transforms pairs. |
| 57 | + |
| 58 | +`lodash.fromPairs()` and `_.fromPairs()` are always checked. |
| 59 | + |
| 60 | +Example: |
| 61 | + |
| 62 | +```js |
| 63 | +{ |
| 64 | + 'unicorn/prefer-object-from-entries': [ |
| 65 | + 'error', |
| 66 | + { |
| 67 | + functions: [ |
| 68 | + 'getObjectFromKeyValue', |
| 69 | + 'utils.fromPairs' |
| 70 | + ] |
| 71 | + } |
| 72 | + ] |
| 73 | +} |
| 74 | +``` |
| 75 | + |
| 76 | +```js |
| 77 | +// eslint unicorn/prefer-object-from-entries: ["error", {"functions": ["utils.fromPairs"]}] |
| 78 | +const object = utils.fromPairs(pairs); // Fails |
| 79 | +``` |
| 80 | + |
0 commit comments