Implementing your own JavaScript Object.entries

Photo by Artem Sapegin

JavaScript Object.entries() method converts an Object into an array of arrays. Each key &value pair from the object is converted into an array and all these arrays will be held inside an array.

For example, If we have an Object with two key & value pairs like below,

const obj = {fruit:’apple’, drink:’coffee’}Object.entries(obj) //[ [ ‘fruit’, ‘apple’ ], [ ‘drink’, ‘coffee’ ] ]

Since we got an array as output, we can easily apply map, filter and reduce methods to it.

Also we can apply Object.entries to primitives

// StringObject.entries(‘apple’) 
// [ [ ‘0’, ‘a’ ], [ ‘1’, ‘p’ ], [ ‘2’, ‘p’ ], [ ‘3’, ‘l’ ], [ ‘4’, ‘e’ ]]

Applying it to Number or Boolean will result in an empty array.

We can iterate over the array using any of the methods. Here i am using map and likewise we can use for, forEach on them.

const obj = {fruit:’apple’, drink:’coffee’}let objArray = Object.entries(obj)objArray.map(entry=>{const [key, value] = entry; //array destructuringconsole.log(`${value} is a ${key}`)})//apple is a fruit
//coffee is a drink

Now lets see how we can create our own Object.entries method

//takes an object as inputObject.myOwnEntries = obj => {
let objKeys=Object.keys(obj); //an array of Object keys
let i = objKeys.length; // i to iterate over the object
let resArray = []; //empty array to hold the results
while(i>0) //using while loop
{
i — ; //iterating backwards
resArray[i]=[objKeys[i],obj[objKeys[i]]] //creating the resultant array
}

return resArray;
}const obj = {fruit:’apple’, drink:’coffee’}Object.entries(obj) //[ [ ‘fruit’, ‘apple’ ], [ ‘drink’, ‘coffee’ ] ]Object.myOwnEntries(obj) //[ [ ‘fruit’, ‘apple’ ], [ ‘drink’, ‘coffee’ ] ]

The reverse is also possible. We can create an object from array of arrays using Object.fromEntries method.

let myEntries= [ [ 'fruit', 'apple' ], [ 'drink', 'coffee' ] ]Object.fromEntries(myEntries)//{fruit: "apple", drink: "coffee"}

We can implement our own formEntries method like below and its easy.

const obj={}myEntries.forEach(a=>obj[a[0]]=a[1])console.log(obj) //{fruit: “apple”, drink: “coffee”}

JavaScript in Plain English

Learn the web's most important programming language.

Radhakrishnan Kanagaraj

Written by

JavaScript in Plain English

Learn the web's most important programming language.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade