14. Object.fromEntries()
This chapter explains the ES2019 feature “Object.fromEntries()
” (by Darien Maillet Valentine).
14.1. Object.fromEntries() vs. Object.entries()
Given an iterable over [key,value] pairs, Object.fromEntries()
creates an object:
It does the opposite of Object.entries()
:
Combining Object.entries()
with Object.fromEntries()
helps with implementing a variety of operations related to objects. Read on for examples.
14.2. Examples
In this section, we’ll use Object.entries()
and Object.fromEntries()
to implement several tool functions from the library Underscore.
14.2.1. _.pick(object, …keys)
pick()
removes all properties from object
whose keys are not among keys
. The removal is non-destructive: pick()
creates a modified copy and does not change the original. For example:
We can implement pick()
as follows:
14.2.2. _.invert(object)
invert()
non-destructively swaps the keys and the values of an object:
We can implement it like this:
14.2.3. _.mapObject(object, iteratee, context?)
mapObject()
is like the Array method .map()
, but for objects:
This is an implementation:
14.2.4. _.findKey(object, predicate, context?)
findKey()
returns the key of the first property for which predicate
returns true
:
We can implement it as follows:
14.3. An implementation
Object.fromEntries()
could be implemented as follows (I’ve omitted a few checks):
function fromEntries(iterable) {
const result = {};
for (const [key, value] of iterable) {
let coercedKey;
if (typeof key === 'string' || typeof key === 'symbol') {
coercedKey = key;
} else {
coercedKey = String(key);
}
Object.defineProperty(result, coercedKey, {
value,
writable: true,
enumerable: true,
configurable: true,
});
}
return result;
}
The official polyfill is available via the npm package object.fromentries
.
14.4. A few more details about Object.fromEntries()
- Duplicate keys: If you mention the same key multiple times, the last mention “wins”.
> Object.fromEntries([['a', 1], ['a', 2]])
{ a: 2 }
- Symbols as keys: Even though
Object.entries()
ignores properties whose keys are symbols,Object.fromEntries()
accepts symbols as keys. - Coercion of keys: The keys of the [key,value] pairs are coerced to property keys: Values other than strings and symbols are coerced to strings.
- Iterables vs. Arrays:
Object.entries()
returns an Array (which is consistent withObject.keys()
etc.). Its [key,value] pairs are 2-element Arrays.Object.fromEntries()
is flexible: It accepts iterables (which includes Arrays and is consistent withnew Map()
etc.). Its [key,value] pairs are only required to be objects that have properties with the keys'0'
and'1'
(which includes 2-element Arrays).
- Only enumerable data properties are supported: If you want to create non-enumerable properties and/or non-data properties, you need to use
Object.defineProperty()
orObject.defineProperties()
.