Search Here

Javascript Object.keys() Method - Get Array of keys from Object and Array

Javascript Object.keys() Method – Get Array of keys from Object and Array

Javascript Object.keys() method returns array of keys on given object.It takes Object or array as argument.

Syntax

Object.keys(obj)

It will return the keys of only those properties/methods whose enumarable property is set to true.

Examples

Using simple Object

person = {
    "fname" : "John",
    "lname" : "snow",
};
Object.keys(person);

//Console Output
(3) ["fname", "lname"]
Retriving keys of Object using Javascript Object.keys()

Retriving keys of Object using Javascript Object.keys()

Object with method get_full_name

person = {
    "fname" : "John",
    "lname" : "snow",
    "get_full_name" : function(){
        console.log(this.fname+" "+this.lname)
    }
};
Object.keys(person);

//Console Output
(3) ["fname", "lname", "get_full_name"]
Object.keys() will also displays function name in key array

Object.keys() will also displays function name in key array

Even function name will also be returned by .keys() method.

Object get_full_name method enumarable property to false

person = {
    "fname" : "John",
    "lname" : "snow",
};
Object.defineProperty(person, "get_full_name", {
    get: function() {
        console.log(this.fname+" "+this.lname)
    },
    enumarable : false
});
Object.keys(person);

//Console Output
(3) ["fname", "lname"]
With Object.defineProperty() method

With Object.defineProperty() method

Object lname property enumarable property to false

person = {
    "fname" : "John",
};
Object.defineProperty(person,'lname', {
    value : "snow",
    enumarable : false
});
Object.keys(person);

//Console Output
(3) ["fname"]
Skipping a property from including into keys by setting enumerable property as false

Skipping a property from including into keys by setting enumerable property as false

Setting option enumarable of property `lname` will exclude it from array.

Using array on Object.keys()

arr = ["one", "two", "three"];
Object.keys(arr);

//Console Output
(3) ["0", "1", "2"]
Using Object.keys() method with array

Using Object.keys() method with array

Using string on `Object.keys()

str = "Javascript";
Object.keys(str);

//Console Output
(10) ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
Using Obejct.keys() on string

Using Obejct.keys() on string

Conclusion

So its time to say good bye we have come to end of our post on Javascript Object.keys() Method – Get Array of keys from Object and Array.If you like our content then please do share it and comment to clarify your doubt.

Related Posts

Summary
Review Date
Reviewed Item
Javascript Object.keys() Method - Get Array of keys from Object and Array
Author Rating
51star1star1star1star1star
Software Name
Javascript Programming
Software Name
Windows Os, Mac Os, Ubuntu Os
Software Category
Web Development