Skip to content

How to get keys from JavaScript Object?

In this post, we will see how to get the key set from the object in JavaScript. Below are some basic methods which I have learnt in my professional software development experience.

Let’s take the below Object for our learning

let map = {"Name" : "Harry", "DOB" : "16.02.1998" , "Age" : "22"};

keys()

Syntax

Object.keys();

This method returns an Array containing the keys of the Object. It maintains the order. If you want want to get the values from object use Object.values()

console.log(map.keys()); //["Name", "DOB", "Age"]

For loop

Using the simple for..loop we can get the keys by iterating each pair in Object.

var keyList = [];
var valueList = [];
for(key in map){
   keyList.push(key);
   valueList.push(map[key]);
}
console.log(keyList);  //["Name", "DOB", "Age"];
console.log(valueList);// ["Harry", "16.02.1998", "22"];

Jquery

Below is the easy approach that would work in Jquery version 1.6+

var keys = [];
keys = $.map(map, function(item, key) {
  return key;
});
console.log(keys); //["Name", "DOB", "Age"];

For each loop

In ECMAScript forEach method, this will iterate over the object and return the keys.

var keyList = [];
Map.forEach(obj => {
keyList.push(obj);
});
console.log(keyList); //["Name", "DOB", "Age"];
See also  What are the possible ways to create objects in JavaScript?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.