javascript - 如何从自身多次调用的函数中返回值?
问题描述
有一些嵌套的对象数据,我必须深入这几个层次,直到找到我的结果。所以我使用了这个findByKey
函数,它会根据需要经常调用自己。然后它应该返回object.source
,但我得到undefined
了。
async function getData(lib, level) {
// First get data from file
const depsBuffer = await readFile(resolve('file.json'))
const deps = JSON.parse(depsBuffer.toString('utf-8'))
// Process data
const result = findByKey(deps.dependencies, deps.dependencies)
console.log(result) // returns undefined :-(
}
function findByKey(data, deps) {
if (data.hasOwnProperty('target') && data.target === 'param') {
return data
}
for (let i = 0; i < Object.keys(data).length; i++) {
const element = data[Object.keys(data)[i]]
if (typeof element === 'object') {
let obj = findByKey(element, deps)
if (obj != null) {
if (RegExp(/.*/).test(obj.source)) return obj.source // <- Return this to `getData`
// else if (!obj?.source?.startsWith('npm:')) findByKey(deps, deps)
}
}
}
}
解决方案
I belive your issue is that
else if (!obj?.source?.startsWith('npm:')) findByKey(deps, deps)
should be
else if (!obj?.source?.startsWith('npm:')) return findByKey(deps, deps)
You are running it recursively, but you are not propagating the return value upward.
推荐阅读
- c++ - 为什么我不能在构造函数中访问已初始化的类成员的方法?
- google-bigquery - 表 JOIN 给出空结果?
- postgresql - 每当在 S3 存储桶上上传新文件时,有没有办法触发 Postgres 函数?
- c# - 将数据类放在棱镜中的位置
- python - 显示谁查看了帖子(用户)
- elasticsearch - Elasticsearch group by 仅返回与每个组内的条件匹配的组
- spring-boot - 使用 Completable Future 使用 Spring Data 从 DB 获取数据时的奇怪行为
- python - Nominatim 如何将海岸上的点分配给一个国家?
- flutter - 在 Dart 中无法接受用户输入
- c# - 从现有的 mysql 数据库创建实体框架内存数据库