The Object.fromEntries() is actually pretty great, thanks for that! Especially the use case you describe, I can see myself using this in a lot of places!
It just sucks that we have to use the "reverse functional" approach, and can't just do Object.entries(myObject).filter(...).toObject() but I guess we can't have it all 😅
Just fiddled around with that idea. Should be as simple as extending the Array.prototype like this:
// Extend Array.prototypeArray.prototype.toObject=function(){returnObject.fromEntries(this.filter(([key,val])=>key));};// Define demo objectconstgermany={countryName:"Germany",capital:"Berlin"};// Use the newly added Array.prototype.toObject() methodObject.entries(germany).filter(([key,val])=>key==="countryName").toObject()// Output: { countryName: "Germany" }
Note that I added just a simple check for the key in the toObject() method. One should add proper checks for valid object keys (e.g. check if the key provided is a string and convert it into a string otherwise, etc.) before usage. 😉
Sure, that works!
But I've never been a fan of extending built-in prototypes - seems like an anti-pattern to me.
It makes code harder to read and understand, and isn't very future proof (just look at #SmooshGate)
The
Object.fromEntries()
is actually pretty great, thanks for that! Especially the use case you describe, I can see myself using this in a lot of places!It just sucks that we have to use the "reverse functional" approach, and can't just do
Object.entries(myObject).filter(...).toObject()
but I guess we can't have it all 😅Just fiddled around with that idea. Should be as simple as extending the
Array.prototype
like this:Note that I added just a simple check for the key in the
toObject()
method. One should add proper checks for valid object keys (e.g. check if the key provided is a string and convert it into a string otherwise, etc.) before usage. 😉Sure, that works!
But I've never been a fan of extending built-in prototypes - seems like an anti-pattern to me.
It makes code harder to read and understand, and isn't very future proof (just look at #SmooshGate)
Totally agreeing with you on that one. 👍