Object.keys() returns an array whose elements are strings corresponding to the enumerable string-keyed property names found directly upon object. This is the same as iterating with a for…in loop, except that a for…in loop enumerates properties in the prototype chain as well. The order of the array returned by Object.keys() is the same as that provided by a for…in loop.
Object.keys() is an ECMAScript6 (ES6) feature.
Example 1:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; const keys = Object.keys(fruits);
Output:
0,1,2,3
Example 2:
const fruits = "Banana"; const keys = Object.keys(fruits);
Output:
0,1,2,3,4,5
Example 3:
const person = { firstName: "John", 
lastName: "Doe", 
age: 50, 
eyeColor: "blue" }; 
const keys = Object.keys(person);
Output:
firstName,lastName,age,eyeColor