Object.entries
allows you to convert an object into an array structure:
console.log(Object.entries({prop1: 1, prop2: 2 }))
// [ ["prop1", 1], ["prop2", 2] ]
This method is part of the ECMAScript 2017 Spec and already heavily used by many developers (including me).
Until recently, there was no convenient method available to transform this structure back into an object.
Now, we finally have Object.fromEntries
which allows constructing an object from the structure returned by Object.entries
.
This makes it super convenient to map objects:
Implementation:
const mapValues = (input, mapper) =>
Object.fromEntries(
Object.entries(input).map(([key, value]) => [
key,
mapper(value, key, input)
])
);
Usage example:
const input = {
prop1: 1,
prop2: 4,
};
const output = mapValues(input, value => value * 2);
expect(output).toEqual({
prop1: 2,
prop2: 8,
});
Support
Browser Support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries#Browser_compatibility
Node Support: https://node.green/#ES2019-features--Object-fromEntries
Top comments (2)
Neat.
However one thing to note is that
Object.entries
ignores all symbol keys. If we want to support symbols:=>
Great job mapping and JavaScript methods of Operations. Modern API's. Gitter Done!!!
Wiltel49@gmail.com
AAS ITI MICHIGAN