Menu Home

Object.keys

Hi everyone, and welcome to another exciting edition of Boring JavaScript! Today, we’ll put you to sleep with Object.keys().

Don’t like to read? Check out our video!

Keys to the Kingdom

In general, Objects are used as collections of key/value pairs, or if you prefer, a collections of properties. Now, I know there are other uses for Objects, but for the purposes of this discussion, we’ll use the definition of a collection of key/value pairs.

Let’s start by looking a a sample object:

const myCat = {
	name: "Fluffy",
	breed: "Himalayan",
	arms: 0,
	legs: 4,
	tail: true,
	weight: 3.58
};

This object has six properties. Each property has two parts – a key and a value. Object.keys() will return an array of all enumerable keys within the object (What are enumerable keys? Good question! Here’s a great MDN article on that).

Let’s see that in action:

const myCatKeys = Object.keys(myCat);

console.log('The keys of the myCat object are:');
console.log(myCatKeys);

/* prints:
The keys of the myCat object are:
[ 'name', 'breed', 'arms', 'legs', 'tail', 'weight' ]
*/

Now you can have an array of all the keys within your object.

Loop the Loop

Once you have your keys in a nice, simple array, you can then loop over that array and get access to each property easily. Consider the following:

const myCat = {
	name: "Fluffy",
	breed: "Himalayan",
	arms: 0,
	legs: 4,
	tail: true,
	weight: 3.58
};

const myCatKeys = Object.keys(myCat);

console.log('myCat properties are:');
myCatKeys.forEach( key => console.log(`Key: ${key}\tValue: ${myCat[key]}`));

/* prints
myCat properties are:
Key: name      Value: Fluffy
Key: breed     Value: Himalayan
Key: arms      Value: 0
Key: legs      Value: 4
Key: tail      Value: true
Key: weight    Value: 3.58
*/

But hold on a minute. Can’t you do the same thing with for … in? Let’s take a look:

const myCat = {
	name: "Fluffy",
	breed: "Himalayan",
	arms: 0,
	legs: 4,
	tail: true,
	weight: 3.58
};

console.log('\n\nmyCat IN properties are:');
for(let key in myCat) {
	console.log(`Key: ${key}\tValue: ${myCat[key]}`);
}

/* prints
myCat IN properties are:
Key: name      Value: Fluffy
Key: breed     Value: Himalayan
Key: arms      Value: 0
Key: legs      Value: 4
Key: tail      Value: true
Key: weight    Value: 3.58
*/

What gives, then? If you can do this using a simple for … in construct, why even bother using Object.keys?

Arrays are da Bomb

It’s because by having your keys within an array, all the methods associated with a standard Array are available to you – methods you can use against the object itself. For example:

const myCat = {
	name: "Fluffy",
	breed: "Himalayan",
	arms: 0,
	legs: 4,
	tail: true,
	weight: 3.58
};

const myCatKeys = Object.keys(myCat);
myCatKeys.forEach( key => console.log(`Key: ${key}\tValue: ${myCat[key]}`));

/* outputs
Key: name      Value: Fluffy
Key: breed     Value: Himalayan
Key: arms      Value: 0
Key: legs      Value: 4
Key: tail      Value: true
Key: weight    Value: 3.58
*/

A common way to determine the number of properties in an object was to use for … in, and simply count the number of times the loop occurred. Using Object.keys(), you now have instant access to the number of properties in your object.

And that’s not all. Think of what you can now do with Array.filter(), Array.some(), or even Array.reduce() – any of the other methods that take a callback function as an argument. By having your keys within an array, you’ve suddenly opened up an entire subset of methods that can be performed automatically on your Object.

The Video

In case you like videos more, here is the link to the video:

Shameless Plug

Be sure to visit us at any of the following locations:

Facebook

YouTube

Twitter

Categories: Boring JavaScript Javascript

Tagged as:

thevirtuoid

Web Tinkerer. No, not like Tinkerbell.

Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: