Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Object creation using ES2019's Object.fromEntries method


    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 Pro 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
    orLog In




    Instructor: 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.

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

    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.

    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.

    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.

    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.

    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.

    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.

    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.