Skip to content

JavaScript object keys() method | Example code

  • by

JavaScript object keys() Returns enumerable properties as an array. Object.keys() takes the object as an argument of which the enumerable own properties are to be returned and returns an array of strings that represent all the enumerable properties of the given object.

Object.keys(obj);

JavaScript object keys()

A simple example code gets the keys of the object into an array in JavaScript.

<!DOCTYPE html>
<html>
<body>

  <script>

    const object1 = {
      name: 'John',
      age: 42,
      agent: false
    };

    console.log(Object.keys(object1));

  </script>

</body>
</html> 

Output:

JavaScript object keys() method

More examples

// Array objects
const arr = ["A", "B", "C"];
console.log(Object.keys(arr)); // ['0', '1', '2']


// array-like objects
const obj = { 65: "A", 66: "B", 67: "C" };
console.log(Object.keys(obj)); // ['65', '66', '67']


// random key ordering
const obj1 = { 42: "a", 22: "b", 71: "c" };
console.log(Object.keys(obj1)); // ['22', '42', '71']


// string => from ES2015+, non objects are coerced to object
const string = "code";
console.log(Object.keys(string)); // [ '0', '1', '2', '3' ]

Do comment if you have any doubts or suggestions on this JS object method.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *