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.