A use case for the Object.entries() method
Andrew McKeever
Posted on February 5, 2020
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
}
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 ]
];
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]);
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.
Posted on February 5, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 25, 2024