DEV Community

Discussion on: 4 Static Object Methods I Wish I Knew About Sooner

Collapse
 
jreinhold profile image
Jeppe Reinhold

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 😅

Collapse
 
ricobrase profile image
Rico Brase

Just fiddled around with that idea. Should be as simple as extending the Array.prototype like this:

// Extend Array.prototype
Array.prototype.toObject = function () {
  return Object.fromEntries(this.filter(([key, val]) => key));
};

// Define demo object
const germany = {
  countryName: "Germany",
  capital: "Berlin"
};

// Use the newly added Array.prototype.toObject() method
Object.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. 😉

Collapse
 
jreinhold profile image
Jeppe Reinhold

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)

Thread Thread
 
ricobrase profile image
Rico Brase

Totally agreeing with you on that one. 👍