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

问题描述 投票:0回答:1

我看到很多人都在询问如何在对象中找到一个对象,所以我想创建一个模块来搜索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语句,如果typeof函数为value。但我似乎无法正确地返回它来执行该函数,特别是如果我们只是在不知道密钥的情况下返回我们找到的第一个函数。

javascript node.js
1个回答
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]()
}

如果您只是想找到第一个函数,可以在边界情况下测试它并返回它。然后,您需要在尝试调用之前测试函数是否返回undefined:

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()
© www.soinside.com 2019 - 2024. All rights reserved.