What's the best way to retrieve a value from a function that invokes itself multiple times?

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)
      }
    }       
  }
}

Answer №1

It seems like the problem lies in

else if (!obj?.source?.startsWith('npm:')) findByKey(deps, deps)

it should actually be

else if (!obj?.source?.startsWith('npm:')) return findByKey(deps, deps)

You are calling it recursively, but failing to pass the return value up the chain.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficiently transmitting WebSockets events/messages to multiple controllers in AngularJS

Incorporating AngularJs, I created a factory to manage a WebSocket connection effectively. Here is the code: .factory('WebSocketConnection', function () { var service = {}; service.callbacks = []; service.connect = func ...

Tips for modifying the href attribute when a user clicks

Is there a way to dynamically change the value of this link <a href="/Countries/388/10">next</a> without having to refresh the page? For example, if a user clicks on the link, it should update to <a href="/Countries/388/20">next</a&g ...

How to extract a variable from a mongoose find method in a Node.js application

Within my Node.js program, I utilize my Mongoose database to query for a specific value in a collection, of which there is only one value present. var myValueX; myCollection.find(function(err, post) { if (err) { console.log('Error ...

Detecting User Interaction with Email Link

On my webpage, there is a link that when clicked, opens the default Email client. I also want to track in my database if the user has clicked on this link or not. Since this interaction occurs at the client-side, I am wondering if there is a way to check ...

Understanding the Parameters for discord.js Slash Commands

I am currently working on a calculation that involves using parameters input through a slash command. While entering the parameters works without any issues, I am facing difficulty in retrieving them. The current code is resulting in an error TypeError: ...

Ways to showcase additional content

When I receive a JSON Object containing posts from a WordPress account, it only includes about 15 posts. What steps can I take to retrieve more than that amount? The structure of the JSON data is as follows: { ID: 4164, title: "24 Hour Non-Stop with Ma ...

Adjusting BackstopJS - Each scenario file is interpreted as an individual scenario rather than a group of scenarios in the configuration file

As I strive to scale BackstopJS by breaking down the original backstop.json file into a directory of structured scenario JSON files, I'm encountering an issue where the function in my config file interprets each JSON file as a single scenario instead ...

Extract TypeScript classes and interfaces from a consolidated file

I am seeking a way to consolidate the export of my classes, interfaces, and enums from multiple files into a single file. In JavaScript, I achieved this using the following method: module.exports = { Something = require("./src/something").default, ...

Iterating over an object using ng-repeat in Angular, where the value is an array

In my data object, I have key-value pairs where the value is an array. Each array contains objects with various properties. $scope.testObj = { "London":[ {"id":1,"city":"London","country":"GB","name":"Test1"}, {"id":4,"city":"London" ...

Eliminating the table header in the absence of any rows

I have successfully implemented a Bootstrap table in my React application, where users can add or delete rows by clicking on specific buttons. However, I want to hide the table header when there are no rows present in the table. Can anyone guide me on how ...

After upgrading from Vuetify version 1.5 to 2.0.18, an issue arises with modules not being found

I encountered the following error: module not found error To address this issue, I took the following steps: Commented out import 'vuetify/src/stylus/main.styl' in the src/plugins/vuetify.js file. Added import 'vuetify/src/styles/main. ...

Enhance your user interface with an interactive Bootstrap dropdown using Angular

I have a program where users can choose from 3 options such as: Hi, Hello and Hey. Currently, when a user selects one of the values, they receive a message saying that they need to "select a value." I am struggling to figure out how to update the ng-model ...

Update the nested radio button to a new value

I have a series of radio button lists generated using ng-repeat. I've managed to capture the selected item successfully. Now, I am attempting to set the default value for the radio buttons. Could someone please provide assistance? Below is my code sni ...

Tips for removing a DOM element in Selenium using Java

Recently, I've been attempting to remove an element from a website using Selenium and Java with the xpath of the element readily available. WebElement m = driver.findElement (By.xpath ("//*[contains(text(),'discord.gg/')]")); The specific e ...

Scripts in iframes within webviews are not preloading and executing properly

When using the <webview> tag in the renderer process within the <body> of a web page, the following code is used: <webview src="http://somewebpage.com" preload="somescript.js"> The script somescript.js will be execute ...

Navigating ngMessages in Angular - Retrieving Data from Multiple Form Fields

Struggling to implement a custom validation function in Angular's ngMessages. My goal is to ensure that the total of two input values always amounts to 100. I've crafted a new directive named totalOneHundred, set to trigger on form changes. How ...

What is the reason for md-grid-list not being created from an HTTP request?

I am trying to make an HTTP request to fetch a JSON data and then use it to dynamically generate an md-grid-list. However, I am encountering issues with this process. The HTTP request is written in my controller. Interestingly, if I substitute md-grid-li ...

"Unpredictable test failures plaguing my Node.js application with jest and supertest

Recently, I've been working on developing a REST API that accepts a movie title in a POST request to the /movies route. The API then fetches information about that movie from an external API and stores it in a database. Additionally, when you make a P ...

Difficulty altering link hover background color

I'm having trouble changing the hover effect background-color on the tweets of this page: Despite my efforts, all the links except for the latest tweets are working perfectly. What am I missing? Here's what I've been trying... <script& ...

Can the `XMLHttpRequest` object stay active when the user switches to a different page?

I am currently facing an issue on my website where users can submit a form using AJAX. The response is displayed in an alert indicating whether the submission was successful or if there were any issues. However, due to the asynchronous nature of this proce ...