How to get an array of function property names from own enumerable properties of an object in JavaScript ?
Enumerable Properties: All the properties of an object that can be iterated using for..in loop or Object.keys() method are known as enumerable properties.
In this article, we will see how to get an array of functions of an object that are enumerable. It can be achieved by following these 2 steps.
In the following implementation for creating a non-enumerable property, we have used Object.defineProperty() method.
Example:
Javascript
<script>
let Person = {
name: "Mahesh" ,
age: 25,
print: function () {
console.log(`${ this .name} ${( this , age)}`);
},
};
Object.defineProperty(Person, "salary" , {
value: "Rs. 50,000" ,
enumerable: false ,
});
Object.defineProperty(Person, "greeting" , {
value: function () {
console.log( "Welcome to GFG" );
},
enumerable: false ,
});
let arr = Object.keys(Person);
let functionsArr = arr.filter((key) => {
return typeof Person[key] === "function" ;
});
console.log(arr);
console.log(functionsArr);
</script>
|
Output:
["name", "age", "print"]
["print"]
Explanation:
In the above code, we have an object named Person with 3 data members (name, age and salary) and 2 functions (‘print’ and ‘greeting’) out of which salary data-member and greeting function are non-enumerable properties.
Property |
Type |
Enumerability |
name |
variable |
enumerable |
age |
variable |
enumerable |
salary |
variable |
non-enumerable |
print |
function |
enumerable |
greeting |
function |
non-enumerable |
Here ‘print‘ is the only function which is enumerable. Using Object.keys(Person) we get an array containing all enumerable properties i.e. [“name”, “age”, “print”] .
Then we used Array.filter() property to filter out all variables so that array has only function property names, i.e. [“print”].
Last Updated :
19 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...