Object.keys method

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

Syntax

let keys = Object.keys(object);

Example

Let's get properties of the following object:

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

The code execution result:

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

Example

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

let 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:

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

Example

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

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

The code execution result:

['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
enru