javascript - 搜索嵌套对象并返回对第一个找到的函数的引用,未知大小,未知名称
问题描述
我看到很多人问如何在对象中查找对象,所以我想制作一个模块,它可以搜索 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 函数作为值。但我似乎无法正确返回它来执行函数,特别是如果我们只是返回我们发现的第一个函数而不知道密钥。
解决方案
您可以将引用和键作为单个对象返回 - 即函数的返回值将是{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()
推荐阅读
- docusignapi - 在使用docusign api发送电子邮件之前检索已经在模板中上传的文档的文档ID
- c++ - CMake 无法找到 gRPC 库,即使它们已安装(mac)
- javascript - 已经在套接字 IO 中排队握手后不能排队握手?
- amazon-s3 - 为什么我的 s3 生命周期规则不生效或不工作
- java - 重置时间选择器
- javascript - 如何将 wixWindow 外形从平板电脑更改为手机?
- mysql - AWS DMS RDS MySQL 8 无法初始化字符集未知
- python - python拆分和重新组合列表的字符串
- java - 有什么办法可以
web.xml 中的标记可以使用 Java 以编程方式(true/false)设置为 Wildfly 集群吗? - c# - 如何在将XML中的子项列表解析为c#中的对象时保留父元素引用