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

Level Up!

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


    Transduce When the Collection Type is an Object

    Paul FrendPaul Frend

    We've seen how we can transduce from arrays or other iterables, but plain objects aren't iterable in Javascript. In this lesson we'll modify our transduce() function so that it supports iterating from plain objects as well, treating each key value pair as an entry in the collection.

    To do this we'll be using a lodash function called entries.



    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




    If the collection we're transducing over is an object, our transduce function isn't going to work. The reason for this is object aren't iterables, so this for-of loop is just going to throw an error. To add support for plain object iteration, let's convert our objects to array pairs.

    Let's rename this collection argument, and then, before our loop, we'll create a variable called Collection. Here we want to check if our collection is a plain object. I'll call isPlainObject, which will take our collection and, if that's true, will call the Lodash helper entries with our collection, but otherwise will just return the collection.

    Entries is the same as the newer object.entries, but I'm running a version of Babel where that's not supported. That's why I'm using entries from Lodash. What it does is, let's say you have an object with keys and values, then after you call entries, what you're going to get back instead is an array where each element is another array, where the first element is the key and the other one is the value. That's why, after calling entries here, we'll still be able to iterate through our collection.

    To test this out, let's create our own version of object.values. We'll call this object Values. The point of this function is to take a source object and pour all of the values into an array. We'll use our Into helper. Our target will be an array. Our transformer should just pull out the values from the object. We'll call map. Here we'll get an array with a key and the value, and we just want to return the value, which is that index one. Our source will be the object.

    Let's try this out. If we call object Values with an object, we should get an array back with just our numbers. We got undefined as our result, so we've missed something. Since we're using brackets in our object values function, we haven't got an implicit return, so let's add that in. Now we get our array with our elements one and two.