简体   繁体   中英

How to access all functions of all nested objects within an object in JavaScript?

I'm importing the [faker][1] library & creating a method to return all [faker][1]'s methods like so:

const faker = require('faker')

const getMethods = obj => Object.getOwnPropertyNames(obj).filter((method) => typeof obj[method] === 'object')

console.log(getMethods(faker))

However, I'm just getting the first level objects :

[
  'locales',        'locale',
  'localeFallback', 'definitions',
  'fake',           'unique',
  'mersenne',       'random',
  'helpers',        'name',
  'address',        'animal',
  'company',        'finance',
  'image',          'lorem',
  'hacker',         'internet',
  'database',       'phone',
  'date',           'time',
  'commerce',       'system',
  'git',            'vehicle',
  'music',          'datatype'
]

I would like to get all methods belonging to these objects instead. [1]: https://www.npmjs.com/package/faker

Thanks for @VLAZ answer, I was able to figure it out using for ...in like so:

const faker = require('faker');

const getObjects = (obj) => {
  return Object.getOwnPropertyNames(obj).filter((method) => typeof obj[method] === 'object' || typeof obj[method] === 'function');
};

const getMethods = (object) => {
  const availableMethods = []; 
  for (const property in object) {
    availableMethods.push(...getObjects(object[property]));
  };

  return availableMethods;
};

getMethods(faker); // returns all methods in an array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM