I need to be able to get all the functions of a class/object on multiple layers. I have only been able to find single-layered methods, but I know this is possible, as JSON.stringify removes every function from an object, so there must be a way to get every function from an object. How would I do this?
const getMethods = (obj) => {
let properties = []
let currentObj = obj
do {
Object.getOwnPropertyNames(currentObj).map(item => properties.push(item))
} while ((currentObj = Object.getPrototypeOf(currentObj)));
return [...properties].filter(item => typeof obj[item] === 'function')
}
var obj = {
a: [],
b: {
e: null,
f: function() {},
g: {
h: function() {},
},
},
c: {
},
d: function() {},
}
console.log(getMethods(obj));
CodePudding user response:
You can use Array#flatMap
with recursion.
let obj = {
a: [],
b: {
e: null,
f: function f() {},
g: {
h: function h() {},
},
},
c: {
},
d: function d() {},
}
function getFunctions(obj) {
return Object.values(obj).flatMap(x => typeof x === 'function' ? x :
typeof x === 'object' && x ? getFunctions(x) : []);
}
console.log(getFunctions(obj));