搜索嵌套对象,并返回对第一个发现的函数的引用,大小未知,名称未知

时间:2019-04-18 15:47:22

标签: javascript node.js

我看到很多人问如何在对象中查找对象,因此我想制作一个模块,该模块可以搜索JSON对象并查找它是否具有键或该属性并返回对该属性的引用。

到目前为止,我有:

  • 查找密钥和/或属性是否存在

我不知道如何搜索大小和形状未知的嵌套对象,如果它找到该键的值的函数,则返回对该键的引用,以便可以对其进行调用。

/*
    @param Object
    @param String, Number, Bool, Type...
    Return a unknown position in an unknown
    nested Object with an unknown size or structure
    a function.
 */
function search(o, q) {
    Object.keys(o).forEach(function (k) {
        if (o[k] !== null && typeof o[k] === 'object') {
            search(o[k]);
            return;
        }
        /* Need e.g. */
        if (typeof k === 'function' || typeof o[k] === 'function') {
            // If functions object name is four, return reference
            return o[k] // Return function() { console.log('Four') } reference
            // We could use return o[k][0] for absolute reference, for first function
        }
        if (k === q || o[k] === q) {
            (k === q) ? console.log(`Matching Key: ${k}`) : console.log(`Matching Value: ${o[k]}`)
        }
        return o[k];
    });
}

let data = {
    1: 'One',
    'Two': {
        'Three': 'One',
    }, 
    'Four': function() {
        console.log('We successfully referenced a function without knowing it was there or by name!');
    }
};

search(data, 'One');
// I would like to also
let Four = search(data, 'Four'); // We might not know it's four, and want to return first function()
// E.g. Four.Four()

但是话又说回来,我们不知道“四个”将是关键。那时我们可以使用if语句if typeof函数作为值。但是我似乎无法正确返回它以执行功能,尤其是如果我们只是返回不知道键就找到的第一个功能。

1 个答案:

答案 0 :(得分:2)

您可以将引用和键作为单个对象返回-即该函数的返回值为{foundKey: someValue}。然后,您可以确定someValue是否是可以调用的函数。例如:

function search(o, q) {
  for (k in o) {
      if (k === q) return {[k]: o[k]}  // return key and value as single object
      if (o[k] !== null && typeof o[k] === 'object') {
          let found =  search(o[k], q)
          if (found) return found
      }       
  }
}

let data = {
  1: 'One',
  'Two': {'Three': 'One',}, 
  'Four': function() {
      console.log('We successfully referenced a function without knowing it was there or by name!')
  }
}

let searchKey = "Four"
let found = search(data, searchKey);

console.log("Found Object", found)

// is it a function? if so call it
if (typeof found[searchKey] == 'function'){
  found[searchKey]()
}

如果您只是想找到第一个函数,可以在边界情况下对其进行测试并返回。然后,在尝试调用该函数之前,需要测试该函数是否返回未定义:

function firstFuntion(o) {
  for (k in o) {
      if (typeof o[k] == 'function') return o[k]
      if (o[k] !== null && typeof o[k] === 'object') {
          let found = firstFuntion(o[k]);
          if (found) return found
      }  
  };
}

let data = {
  1: 'One',
  'Two': {
      'Three': 'One',
  }, 
  'Four': function() {
      console.log('We successfully referenced a function without knowing it was there or by name!');
  }
};

let found = firstFuntion(data);

// firstFuntion should return a function or nothing
if (found) found()