Skip to main content

Object.keys() Method – Copy an Object's Keys into an Array

Whenever you use Object.keys() on a JavaScript object, the method does the following:

  • It creates a new array.
  • It copies the specified object's enumerable own keys into the newly created array.
  • It returns the new array containing string items representing the given object's keys.

Syntax of the Object.keys() Method

Object.keys() accepts a single argument. Here's the syntax:

Object.keys(objectArgument);

The objectArgument refers to the JavaScript object whose keys (property names) you want to extract into a new array.

note

The Object.keys() method does not alter the original object.

Examples of the Object.keys() Method

Below are examples of the Object.keys() method.

Copy an object's keys into a new array

const profile = {
firstName: "Oluwatobi",
lastName: "Sofela",
companyName: "CodeSweetly",
npmPackage: "@codesweetly/react-youtube-playlist",
id: 9103,
};

const formFieilds = Object.keys(profile);

console.log(formFieilds);

// The invocation above will return:
// ["firstName", "lastName", "companyName", "npmPackage", "id"]

Try Editing It

Copy an array's keys into a new array

const myBio = ["Oluwatobi", "Sofela", "CodeSweetly", 9103];

const keysInMyBio = Object.keys(myBio);

console.log(keysInMyBio);

// The invocation above will return:
// ["0", "1", "2", "3"]

Try Editing It

Copy a string's keys into a new array

const firstName = "Oluwatobi";

const keysInFirstName = Object.keys(firstName);

console.log(keysInFirstName);

// The invocation above will return:
// ["0", "1", "2", "3", "4", "5", "6", "7", "8"]

Try Editing It

The Object.keys() method successfully extracted the string's keys because strings are the only primitive data with enumerable own properties.

tip

Overview

This article discussed what the Object.keys() method is. We also used examples to see how it works.

Join CodeSweetly Newsletter