Transforming objects using the Object.entries and Object.fromEntries methods

Wojciech Trawiński
JavaScript everyday
2 min readJun 23, 2019

Transforming arrays can be easily accomplished with the aid of the built-in Array.prototype.map method. However, mapping an object wasn’t such a breeze before the Object.fromEntries method was introduced, which together with the Object.entries method makes it a trivial task.

Transforming arrays

If you have an array containing prices, you can simply map each value (e.g. double it) using the built-in map method available for every instance of the Array class via prototype:

Transforming objects w/o the Object.fromEntries

When it comes to objects, it’s not as easy as for arrays. First, you need to obtain an array of object’s entries using the self-explanatory Object.entries method. From now on, you work with an array containing two-elements arrays. Therefore, transformation may be accomplished with the aid of the Array.prototype.map method. Last but not least, the resulting array needs to be converted to an object, which can be performed using the Array.prototype.reduce method with an appropriate accumulator function:

Transforming objects with the Object.fromEntries

Fortunately, you can take advantage of the Object.fromEntries method in order to get rid of the manual array-to-object conversion:

Feel free to play around with the examples:

I hope you liked the post and learned something new. If so, please give me some applause 👏

--

--