Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get ALL methods/functions in a class/object

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));

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading