Sometimes, we want to get an object’s methods with JavaScript.
In this article, we’ll look at how to get an object’s methods with JavaScript.
How to get an object’s methods with JavaScript?
To get an object’s methods with JavaScript, we can use the array filter method and Object.keys method.
For instance, we write
const myObj = { myFn() {}, abc: true };
const allKeys = Object.keys(myObj);
const fnKeys = allKeys.filter((key) => typeof myObj[key] == "function");
console.log(fnKeys);
to call Object.keys with myObj to get an array of property kets in myObj as a string array.
Then we call allKeys.filter with a callback that checks if myObj[key] is a function with the typeof operator.
And an array of method keys are returned by filter.
Conclusion
To get an object’s methods with JavaScript, we can use the array filter method and Object.keys method.