Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

    Object creation using ES2019's Object.fromEntries method

    Thomas GrecoThomas Greco

    This lesson shows how to use ES2019's Object.fromEntries method to convert [key,value] array pairs stored inside of a Map into an object.

    Following this, we'll check out how we can use Object.fromEntries along with Object.entries to implement lodash's pick and invert functions using native JavaScript.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: 00:01 On our page we see that we have this MyMap variable, which is being set to a map. Inside here, we're using arrays to start our key-value pairs.

    00:14 Blow this. I'm going to create this MyObject variable and then use Object.fromEntries() to convert our map to an object.

    00:22 If we look at our output, we'll see that all these array values have been transformed into the key-value pairs inside of an object.

    00:34 Moving forward, let's see if we can use Object.fromEntries() along with Object.entries() to create some helper function. Here, I'm creating a function called pick which is going to take in an object as well as array of keys.

    00:51 We're then going to use Object.fromEntries(). Inside here is where we're going to use our Object.entries() call. This is going to loop through our input object. Then we're going to filter through the key-value pairs that it iterates over. We want to filter out any keys that haven't been specified via the keys array being input to our function.

    01:19 Now we've run pick and pass in my object that we created before. The properties will pass in are just first name, last name and email. We'll see that an object is returned to us, which includes only those key-value pairs.

    01:37 We should note that pick isn't going to modify our original MyObject. Rather, it's going to return a shallow copy containing only the keys and values that we need.

    01:50 Next, I'm going to implement an invert function which is going to take in object and return again Object.fromEntries(). Inside this we'll again use Object.entries(). Instead of filter though, we'll use map to swap every key-value pair inside of our object.

    02:14 As a result of this, when we call invert and pass in a, give it a value of 1, and then b, a value of 2, then executing invert will swap these values. Now 1 and 2 are our keys and a and b are the corresponding values.