Object.keys method

The Object.keys method returns an array of object properties in the same order as when iterating through a loop.

Syntax

javascriptlet keys = Object.keys(object);

Example

Let's get properties of the following object:

javascriptlet obj = {'a': 1, 'b': 2, 'c': 3};
console.log(Object.keys(obj));

The code execution result:

javascript['a', 'b', 'c']

Example

And now put the properties in an object in random order:

javascriptlet obj = {2: 'b', 1: 'a', 4: 'd', 3: 'c'};
console.log(Object.keys(obj));

After executing the code, we will see that the properties are sorted in ascending order:

javascript['1', '2', '3', '4']

Example

Also, using the Object.keys method, you can get the positions of array elements:

javascriptlet arr = ['a', 'b', 'c', 'd'];
console.log(Object.keys(arr));

The code execution result:

javascript['0', '1', '2', '3']

See also

  • the Object.values method
    that returns an array of object values
  • the Object.assign method
    that copies properties and values of an object