There is some nested object data and I have to go through this several level deep until I find my result. So I use the findByKey
function, which is calling itself as often as it is needed. Then it should return object.source
, but I get undefined
instead.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.