gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:04:45 24 4
gpt4 key购买 nike

我看到很多人询问如何在对象中查找对象,因此我想制作一个模块,可以搜索 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 函数来获取值。但我似乎无法正确返回它来执行该函数,特别是如果我们只是在不知道 key 的情况下返回我们找到的第一个函数。

最佳答案

您可以将引用和键作为单个对象返回 - 即函数的返回值将是 {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()

关于javascript - 搜索嵌套对象并返回对第一个找到的函数的引用,未知大小,未知名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55749607/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com