I am unable to give back an item

I am working with an object structure that looks like this:

const obj = {
  name: 'john',
  children: [
    {
      name: 'Foo'
    },
    {
      name: 'Bar',
      children: [
        {
          name: 'Doe'
        }
      ]
    }
  ]
}

My task is to create a function that can locate and return the object with a specified name. Currently, my code is able to find objects by name, but it does not successfully return the located object.

const search = (node, name) => {
  return searchInObj(node, name);
};

const searchInObj = (obj, name) => {
  if (obj.name === nodeName) {
    return obj;
  } else {
    if (obj.children) {
      searchInArr(obj.children, name);
    }
  }
};

const searchInArr = (arr, name) => {
  for (let i = 0; i < arr.length; i++) {
    searchInObj(arr[i], name);
  }
};

When I test it with

console.log(search(obj, 'Doe')) // returns undefined

The function only works as expected when searching for john

Answer №1

Retrieve the outcome of the searchInObj function.

  const tree = {
  name: 'john',
  children: [
    {
      name: 'Foo'
    },
    {
      name: 'Bar',
      children: [
        {
          name: 'Doe'
        }
      ]
    }
  ]
}

const findNode = (node, name) => {
  return searchInObj(node, name);
};

const searchInObj = (obj, name) => {
  if (obj.name === name) {
    return obj;
  } else {
    if (obj.children) {
      return searchInChildren(obj.children, name); 
    }
  }
};

const searchInChildren = (arr, name) => {
  for (let i = 0; i < arr.length; i++) {
    const result = searchInObj(arr[i], name);
    if (result !== undefined) return result
  }
};

console.log(findNode(tree, 'Doe')) ///This will output the object

Answer №2

Make sure to incorporate return statements as advised by @quentin

const obj = {
  name: 'mary',
  children: [
    {
      name: 'Alice'
    },
    {
      name: 'Bob',
      children: [
        {
          name: 'Eve'
        }
      ]
    }
  ]
}

const search = (node, name) => {
  return performSearch(node, name);
};

const performSearch = (obj, name) => {
  // Is there a mistake with nodeName?
  if (obj.name === name) {
    return obj;
  } else {
    if (obj.children) {
      // Don't forget to include the return statement
      return searchInArray(obj.children, name);
    }
  }
};

const searchInArray = (arr, name) => {
  for (let i = 0; i < arr.length; i++) {
    // Return once found
    const result = performSearch(arr[i], name);
    if (result !== undefined) return result
  }
};

console.log(search(obj, 'Eve'))

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

What are some tips for increasing your points on the journey using Here Maps?

While plotting a route, I noticed that the segments on highways are quite far apart. Is there a way to get a more detailed routing with finer points along the journey? $.ajax({ url: 'https://route.cit.api.here.com/routing/7.2/calculateroute ...

Sending Image Data in Base64 Format with Ajax - Dealing with Truncated Data

My current challenge involves sending Base64 image data through ajax to the Server. I've noticed that sometimes all the pictures are successfully sent, but other times only a few make it through. Does anyone have suggestions on how to implement error ...

"Navigate with ease using Material-UI's BottomNavigationItem and link

What is the best way to implement UI navigation using a React component? I am currently working with a <BottomNavigationItem /> component that renders as a <button>. How can I modify it to navigate to a specific URL? class FooterNavigation e ...

Using Rails to render a partial containing a form object

I need help with rendering a partial called 'colordata' after selecting a color from a dropdown list using Ajax. Unfortunately, I'm not seeing any changes on the main page and the form is undefined in the colordata partial. This is the sche ...

What is the recommended return type in Typescript for a component that returns a Material-UI TableContainer?

My component is generating a Material-UI Table wrapped inside a TableContainer const DataReleaseChart = (): React.FC<?> => { return ( <TableContainer sx={{ display: 'grid', rowGap: 7, }} > ...

consolidating express routes in one consolidated file

I am attempting to consolidate routes into a single file using app.use app.js import express from 'express' import testRouter from 'testRouter' const app = express() app.use('/testRouter', testRouter) app.listen(3000) tes ...

How can I retrieve the text from two DIV elements simultaneously using JS/jQuery?

Is there a way to loop through all <TD> elements in order to store the Title and Link from each element into separate variables using JavaScript / jQuery? Sample HTML: <td> <div class="class_Title row border-bottom" name="name_Title" i ...

The select dropdown does not automatically refresh when the array value changes

I am facing an issue with a select dropdown that is populated by an array filled with data from the server response: myApp.controller('mController', function($scope, $routeParams, $http, contextRoot) { var dataObject = {} $scope.arr = [ ...

Steps for executing a Node script are as follows:

My task is to execute a node script that will remove an object from an external API. This can be achieved by running the following command: node server.js Customer55555 Upon execution, the specified object should be deleted successfully. To interact wit ...

Creating a header for an HTML table with merged columns in jQuery DataTables

Whenever I attempt to implement the jQuery DataTables plugin, it encounters an error stating c is undefined on line 256 (as seen in the minified version). The structure of my table is as follows: <table class="datatable"> <thead> ...

JavaScript is throwing an error when clicking on functions and managing the z-index property

I am experiencing difficulties with my website code. I have defined all the necessary functions and CSS, but I keep encountering errors such as "clicked is not defined," even though it is clearly present in the script. The goal of the code is to bring the ...

NextAuth - simulating the login process of OneLogin

I've been working on setting up a local OneLogin mocked service using WireMock. Everything has been going smoothly so far, as I was able to mock most of the OAuth OneLogin flow. However, I'm facing an issue with the last part that is preventing i ...

Automated algorithm inspecting a variety of hyperlinks

Recently, I've developed an innovative anti-invite feature for my bot. However, there seems to be a minor glitch where the bot fails to remove any links sent within the enabled guild when the command is triggered. This issue specifically occurs in ver ...

What is the best way to generate a consistent and unique identifier in either Javascript or PHP?

I attempted to search for a solution without success, so I apologize if this has already been discussed. Currently, I am in need of an ID or GUID that can uniquely identify a user's machine or the user without requiring them to log in. This ID should ...

How can I send two responses in a single POST request using node.js?

Below is my router setup for handling responses: questionRouter.post('/questionsReply', (req, res) => { twilioResp(req, res); var newResponse = new Response(req.body); newResponse.save((err, data) => { if (err) return handleDBError(er ...

What should I do to resolve the error message TypeError: _components_firebase_Firebase__WEBPACK_IMPORTED_MODULE_2__.default.auth is not a valid function?

I have implemented Firebase with next.js and organized my files as shown below. However, I am encountering an issue with using the firebase client side SDK during the sign-up process. Firebase.js is where the firebase app is initialized import firebase fr ...

Is it possible to automatically redirect to a different URL if the server is running slow when clicking?

Is it possible to utilize Javascript, AJAX, or another client-side technology to automatically redirect the user to a different URL if the initial URL is slow to respond when clicked on? For example, if a link redirects to URL1 and there is no response fr ...

Check for the presence of an Outlook add-in within a web application

I'm having trouble determining whether my hosted web application is being accessed through a browser or from within the Outlook 2013/2016 client. I have developed a web application that offers different functionalities depending on whether it is acce ...

Why does Asp.net Webform load twice every time I click on the form link?

In my asp.net webform project, I am encountering an issue where the page is running twice when clicked. The problem arises when calling two functions (Fill DropDowns) on the Page_Load Event. During debugging, it was observed that the control enters the Pa ...

Error: React Native Component Exception - a potential hiccup in

As a newcomer to React Native, I've encountered an issue while trying to bind data from a local JSON server API. Everything worked fine when I used a class component for my EventList, but after integrating Navigation in App.js and changing it to a fun ...