How to Use the Object.keys() Method in JavaScript | Plantpot

How to Use the Object.keys() Method in JavaScript

Web Dev
Sponsored links

In this article, I will introduce how to use the Object.keys() method in JavaScript.

The Object.keys() method

The Object.keys() method is a method that extracts only the keys from a variable of type Object.
You can extract name and age from the variable {name: 'Michael', age: 20}.

The Object.keys () method can extract an array of keys only by specifying the target for which you want to extract keys as an argument.

const target = {
  name: 'Michael',
  age: 20,
  country: 'Japan',
  city: 'Tokyo',
};

Object.keys(target);
// => ['name', 'age', 'country', 'city']

In the following cases, {1: 'football', 2: 'baseball'} under hobbies cannot be extracted because it is the value of hobbies.

const target = {
  name: 'Michael',
  age: 20,
  country: 'Japan',
  city: 'Tokyo',
  hobbies: {
    1:'football',
    2:'baseball',
  },
};

Object.keys(target);
// => ['name', 'age', 'country', 'city', 'hobbies']

Also note that if the key is a number (or a string that means a number), it will be sorted numerically.

const target = {
  2:2,
  1:1,
  3:2,
};

Object.keys(target);
// => ['1', '2', '3']