Getting all the keys from an object in javascript
Object.keys is a built-in javascript method used to get all the keys from an object. You just have to pass the object as a parameter. Here is an example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const object1 = { name: 'John', age: 42, profession: "Software Engineer", isActive : false }; console.log(Object.keys(object1)); // output : Array ["name", "age", "profession", "isActive"] |
The output of the above code will be :
Array [“name”, “age”, “profession”, “isActive”]
Using Object.keys method with an array
You can use this method with an array to get all the indexes from an array. An array will be passed as a parameter instead of an object. Here is an example.
1 2 3 4 5 6 7 |
const arr = ['Javascript', 'React', 'React Native']; console.log(Object.keys(arr)); // output :<em>Array ["0", "1", "2"]</em> |
The output of the above code will be
Array [“0”, “1”, “2”]
What is the return type of Object.keys?
An array of strings is the return type of object.keys method. This array of strings has all the keys of an object or indexes if an array was passed as a parameter.
For more details please check developer.mozilla.org
Conclusion
Object.keys method is a built-in JavaScript function that can extract all the keys from an object or array. It returns a new array with all the keys of an object or array. It expects a parameter that can be an array or object.
Also check : How to merge two objects in javascript