Object.keys() Method

  • Object Method
  • Object Methods
  • Code
  • JavaScript

Going hand in hand with Object.values() is Object.keys(). Where Object.values() gave us the values from a data object, I'm sure you can guess what Object.keys() outputs. That's right, it's the keys in the key-value pairs. I hope you'll forgive me if I just recycle the examples I used in my previous blog post.

const person = {  name: "Joey",  age: 31,  occupation: "Web Developer",  location: "Austin, Texas",  hungry: true,};
const objKeys = Object.keys(person);console.log(objKeys);// expected output:// ["name", "age", "occupation", "location", "hungry"]

If Object.values() method gives us a way to unpack the contents of a box then...hm. This analogy probably doesn't hold up, but Object.keys() gives us what could probably be the tape that holds the contents in the box? lol idk about that.

The above code produces the same result as this for...in loop:

const objKeys = [];
for (const attribute in person) {  objKeys.push(attribute);}console.log(objKeys);// expected output:// ["name", "age", "occupation", "location", "hungry"]

The same gotcha applies when it comes to numeric keys: Object.keys() will output the items in their numeric order.

const obj = {  5: "Giraffe",  70: "Octopus",  17: "Lion",  1: "Armadillo",  0: "Puffin",};
const objKeys = Object.keys(obj);console.log(objKeys);// expected output:// ["0", "1", "5", "17", "70"]

One last thing to note, if you run the Object.keys() method against a simple array, you get its index values:

const colors = ["red", "orange", "yellow", "green", "blue", "violet"];
const objKeys = Object.keys(colors);console.log(objKeys);// expected output:// ["0", "1", "2", "3", "4", "5"]

From MDN: The Object.keys() method returns an array of a given object's own property names, in the same order as we get with a normal loop.

See more examples and documentation here.