My task involves navigating through nested object data to find a specific result. I am using the findByKey
function, which recursively calls itself until the desired result is found. However, instead of returning object.source
, I am getting undefined
.
async function getData(lib, level) {
// Retrieve data from a file
const depsBuffer = await readFile(resolve('file.json'))
const deps = JSON.parse(depsBuffer.toString('utf-8'))
// Process the data
const result = findByKey(deps.dependencies, deps.dependencies)
console.log(result) // unfortunately, it 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 // <- This should be returned to `getData`
// else if (!obj?.source?.startsWith('npm:')) findByKey(deps, deps)
}
}
}
}