Categories
JavaScript Answers

How to Print All Methods in a JavaScript Object?

Spread the love

To print all methods in a JavaScript object, we can use the Object.keys method to get all the top-level property keys of the JavaScript object in an array.

Then we call the filter method to filter out the keys for values that aren’t methods with the typeof operator.

Then we map the method keys to methods with map .

For instance, we can write:

const getMethods = (obj) => {
  return Object.keys(obj)
    .filter((key) => typeof obj[key] === 'function')
    .map((key) => obj[key]);
}

const obj = {
  foo() {},
  bar: 1
}
console.log(getMethods(obj))

We have the getMethods function that takes an obj object.

Then we call Object.keys with obj to get the top-level string property keys.

Then we call filter with a function that returns the properties that are functions with the typeof operator.

Next, we call map to map each key to their corresponding value.

Therefore, if we call getMethods with obj , we get the foo method in the array.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *