Javascript Object Keys Method Loop Through Enumerable Properties
Learn how to use Javascript Object Keys Method to Loop Through Enumerable Properties
Published
Javascript Object Keys
Enumerable properties are those properties whose internal enumerable flag is set to true, which is the default for properties created via simple assignment or via a property initializer. Enumerable properties show up in for…in loops unless the property’s key is a Symbol.
The Object.keys() method returns an array of a given object’s own enumerable property names, iterated in the same order that a normal loop would.
Object Keys Syntax
Object.keys(object)
Object: The object of which the enumerable’s own properties are to be returned.
Return value: An array of strings that represent all the enumerable properties of the given object.
Example Of Object Keys
In javascript enumerable is the default properties created via simple assignment. Here, we can calling Object Keys which will return an array of only enumerable properties available in an object. Once you run the example you will find that getProperty is not a enumerable property but enumerableProperty is.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="result"></div>
<script>
//getProperty is a property which isn't enumerable
//enumerableProperty is a property which is enumerable
var myObj = Object.create({}, {
getProperty: {
value: function () { return this.enumerableProperty; }
}
});
myObj.enumerableProperty = 1;
document.getElementById("result").innerHTML = Object.keys(myObj)
</script>
</body>
</html>