【问题标题】:How to access all functions of all nested objects within an object in JavaScript?如何在 JavaScript 中访问对象内所有嵌套对象的所有函数?
【发布时间】:2021-10-02 16:11:27
【问题描述】:

我正在导入 [faker][1] 库并创建一个 method 以返回所有 [faker][1] 的 methods,如下所示:

const faker = require('faker')

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

console.log(getMethods(faker))

但是,我只是获得第一级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'
]

我想获取属于这些objects 的所有methods。 [1]:https://www.npmjs.com/package/faker

【问题讨论】:

  • 所以递归到它们...
  • 递归或使用for...in。如果你需要 all 包括不可枚举的,那么你需要递归 + Object.getOwnPropertyDescriptors

标签: javascript arrays object methods faker


【解决方案1】:

感谢@VLAZ 的回答,我可以像这样使用for ...in 来解决这个问题:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-12
    • 1970-01-01
    • 2017-06-18
    • 2020-02-21
    • 1970-01-01
    • 2021-12-29
    • 2013-09-05
    • 1970-01-01
    相关资源
    最近更新 更多