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)
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. 👍