DEV Community

Cover image for A use case for the Object.entries() method
Andrew McKeever
Andrew McKeever

Posted on

A use case for the Object.entries() method

Perhaps you already know about Object.keys() and Object.values() to create an array of an objects keys and values respectively. However, there's another method Object.entries() that will return a nested array of the objects key and values. This can be very helpful if you'd like to return only one of these pairs based on the other's value.

A clean way to return keys in an Object

Often times in form with form data there will be a list of choices presented to users that are selectable with radio buttons. The object's data returned from this will look something like this...


const myListValues = {
  'selectionTitle': true,
  'anotherSelectionTitle': false
}
Enter fullscreen mode Exit fullscreen mode

We could store these objects with their keys and value in our database as they are, however just adding the key name for any truthy value would be sufficient. By passing our myListValues object into Object.entries() we can filter out any falsey values from our newly created array and then
return the keys as a string.

Execution

We'll make use of not only Object.entries(), but also the very handy array methods filter() and map(). The output from Object.entries(myListValues) will be...


 const separatedList = [
   ['selectionTitle', true ], 
   ['anotherSelectionTitle', false ]
 ]; 
Enter fullscreen mode Exit fullscreen mode

We now have an array that can be utilise .filter() and .map() to return our desired result. So let's clean up our separatedList array a bit.


 const separatedFilteredList = 
   Object.entries(myListValues).filter([key, value] => value);

 const selectedItems = separatedFilteredList.map(item => item[0]);
Enter fullscreen mode Exit fullscreen mode

There we have it. Our selectedItems array is now just a list of the key names from our objects who's value was truthy. This is just one of many use cases for perhaps a lesser know object method. I'd love to see some more interesting use cases you may have come up with.

Top comments (5)

Collapse
 
mjsarfatti profile image
Manuele J Sarfatti

And another of my favourite uses of Object.entries():

for (const [key, value] of Object.entries(obj)) {
    console.log(`${key}: ${value}`);
}

I love the conciseness and expressiveness...

Collapse
 
leandroruel profile image
Leandro RR

nice 💐

Collapse
 
lindaojo profile image
Linda

Wonderful article Andrew. You explained well.

Collapse
 
keevcodes profile image
Andrew McKeever

Thank you Linda, I hope it helped you

Collapse
 
lindaojo profile image
Linda

Yes it did. I am writing about some array methods and wanted to go deeper into entries(). Thank you