Open In App

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:




<script>
  
    // Person object has name, age, salary
    // and print properties 
    // Except salary, all properties are enumerable
    let Person = {
        name: "Mahesh",
        age: 25,
        print: function () {
            console.log(`${this.name} ${(this, age)}`);
        },
    };
  
    // salary- non enumerable property
    Object.defineProperty(Person, "salary", {
        value: "Rs. 50,000",
        enumerable: false,
    });
  
    // greeting- non enumerable function
    Object.defineProperty(Person, "greeting", {
        value: function () {
            console.log("Welcome to GFG");
        },
        enumerable: false,
    });
  
    // arr contains all the enumerable
    // properties of Person
    let arr = Object.keys(Person);
  
    // functionsArr contains enumerable
    // function properties of Person.
    // typeof returns an string representing
    // data type.
    // Using filter() method to filter the array
    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”].


Article Tags :