So lets say I have an object like this:
myObject = {
key1: "foo",
key2: "",
key3: "bar",
key4: "foobar",
key5: undefined
}
and I want an array of the keys, but only if the have a value. i.e. if they’re undefined or empty string, I don’t want them included in the array.
Currently I’m using Object.keys(myObject)
but this gets all the keys including those that are undefined/falsy.
I completely understand I can likely write my own version of the keys method from Object, but I’m wondering if theres an easier way than that.
Filter the entries by whether the key portion of the entry is truthy, then map to the keys:
If all you care about are the truthy keys you can use a somewhat simpler filter than above:
You only need to use Array.filter() to remove the keys that have nullable results
try it.
This will also cut out other falsy values however, such as
0
,NaN
,null
,false
. If you very specifically are guarding against empty strings and undefined:Explanation:
I don’t know if there is another way but you can try something like this
There’s a couple ways to do that. You could use filter:
Or a for loop:
You could also be fancy and extend Object by creating a class. But I believe that would be overkill 😀