DEV Community

Cover image for 4 Static Object Methods I Wish I Knew About Sooner
Sandrico Provo
Sandrico Provo

Posted on

4 Static Object Methods I Wish I Knew About Sooner

When it comes to writing code in JavaScript, objects are a massively important and useful part of the language. If you haven't learned about objects yet that's okay! You can think of an object as a way for us to create a collection of key-value pairs. For example, I have a first and last name, and a city I live in. These would be the keys of key-value pairs. The values would be the pieces of information with first name being Sandrico, last name being Provo, and city being Halifax. Here is what that would look like inside an object.

let myInfo = {
  firstName: "Sandrico",
  lastName: "Provo",
  city: "Halifax"
}
Enter fullscreen mode Exit fullscreen mode

Objects have sooooo many use cases in JavaScript, and the example above is just one scenario where you might use them. Another cool thing about objects is that whenever we make one it has a collection of methods attached to it called static methods. What are static methods you might ask πŸ˜ƒ? Well, Static methods are pre-defined methods we have access to on every object. There is a master object class that every object inherits these methods from, somewhat like a blueprint. Another metaphor would be a car. Every car you buy these days has certain base features like a seat belt and steering wheel, and static methods are the same idea! When I started learning about objects I didn't learn about static methods until later. The static methods we are about to go through would have helped me a ton if I knew about them sooner, but now I hope they save you some time when coding πŸ˜„.

TLDR

Name Description
JavaScript Object A JS class that lets us define an object data type. It lets us create a collection of key-value pairs.
Object Static Methods Methods that are pre-defined and called on the object class.
Object Instance Methods Methods that are pre-defined and called on a single object instance.
Object.keys() Returns an array of the objects keys.
Object.assign() Copies a source objects properties to a target object.
Object.entries() Returns an array of all the objects key-value pairs.
Object.fromEntries() The opposite of .entries(), this turns a key-value pair list into an object.
Object.prototype.hasOwnProperties() Returns true or false based on whether the object has the given key.

The Static Methods

Let's set up an example for us to work with.

let countryCanada = {
    countryName: "Canada",
    capital: "Ottawa",
    region: "North America",
    population: 37590000,
    neighbour: "United States"
}
Enter fullscreen mode Exit fullscreen mode

Object.keys()

Sometimes when you're working with an object you might want to list all of its keys. Object.keys() is the method that lets us do this! When you use Object.keys() you get back an array that contains all of that objects' keys. Fun fact: the array that you get back should be in the same order as the object that the keys are in. Here's what this would look like in code.

let propertiesArray = Object.keys(countryCanada);
// Output: ['countryName', 'capital', 'region', 'population', 'neighbour']
Enter fullscreen mode Exit fullscreen mode

Object.assign()

Sometimes you might want to make a copy of an object and its key-value pairs. Object.assign() lets us do this by copying key-value pairs from a source object to a target object. The target object can be empty or an object with its own properties already. If the target object has its own properties, you do need to be careful because if the source and target have a matching property the sources value will overwrite the targets value. Another tip is that you can also have multiple sources! Let's check out an example.

// Make a copy using Object.assign()
let copiedCountry = Object.assign({}, countryCanada);
console.log(copiedCountry);
// Output: copiedCountry { countryName: "Canada", capital: "Ottawa", region: "North America", population: 37,590,000, neighbour: "United States" }
Enter fullscreen mode Exit fullscreen mode

Object.entries()

This static method allows you to convert your objects into arrays. If we did this with our example object, here is what the output would look like.

let convertedCountryArray = Object.entries(countryCanada);
// Output: [["countryName", "Canada"], ["capital", "Ottawa"], ["region", "North America"], ["population", 37590000], ["neighbour", "United States"]]
Enter fullscreen mode Exit fullscreen mode

As you can see, the output array is a 2D array (an array with arrays nested inside of it). One benefit of working with this object as an array is that you could use the vast array (πŸ™ŠπŸ˜…) of array methods to manipulate it. Now, you've converted this object into an array, but what if you want to convert it back into an object? Well, there is a method for that as well!

Object.fromEntries()

You can think of this method as doing the reverse of Object.entries(). It takes an array and converts it into an object. If we used this on our counvertedCountryArray from our Object.entries() example, we would be back to our original object like so.

let reconvertedCountryArray = Object.fromEntries(convertedCountryArray);
console.log(reconvertedCountryArray);

// Output: countryCanada = { countryName: "Canada", capital: "Ottawa", region: "North America", population: 37590000, neighbour: "United States" }
Enter fullscreen mode Exit fullscreen mode

An example of what this could allow us to do is manipulate this object using array methods. Let say we want a new object that only has the capital city in it. In combination with Object.entries(), we could use this method to achieve this. Here is an example of what I mean.

let manipulatedObject = Object.fromEntries(
  Object.entries(countryCanada).filter(([key, value]) => { 
    if (value === "Ottawa") return [key, value];
  }
));
// Output: { capital: "Ottawa" }
Enter fullscreen mode Exit fullscreen mode

Bonus: Object.prototype.hasOwnProperty() Instance Method

Here are a two terms that'll help explain our bonus example.

Name Description
Prototype The prototype is what JS objects use to inherit methods/functions and other features from one another.
Instance Method Instance methods are methods built onto objects that run on the particular instance of an object instead of the object class.

Object.prototype.hasOwnProperty() is a useful method because it allows us to check whether or not the object we are working with has a particular property in it. An important fact to remember is that this method checks if the object owns the property we're looking for as oppose to inheriting it. Here is an example.

let isPropertyOwned = countryCanada.hasOwnProperty("capital");
console.log(isPropertyOwned);
// Output: true
Enter fullscreen mode Exit fullscreen mode

Like many things in coding there are multiple ways you could do a check like this, but it's nice to have a built-in function to help you out πŸ‘πŸΎ.

Well That Was Fun πŸ˜„

There we are. We've looked at Object.keys(), .assign(), .entries(), .fromEntries() and .hasOwnProperty(). These methods could have saved me time when I was starting out, so hopefully they help you save some time in your journey.

Happy Learning πŸ˜„πŸ‘‹πŸΎ!

Discussion (7)

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. πŸ‘

Collapse
asyraf profile image
Amirul Asyraf

Awsome explanations, Thanks dude 🀟

Collapse
sandricoprovo profile image
Sandrico Provo Author

Glad you liked them, thanks 😊😊!

Collapse
tilakmaddy_68 profile image
Tilak Maddy

BONUS:

Object.freeze(myObj);

If you do this the properties of myObj cannot be changed later on :)