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

Utilizing CSS classes based on subelements

I need to assign css classes to items in a list based on certain criteria. Here is an example of the structure I am working with: <ul ng-controller="Navigation"> <li><a href="#">Category A</a> <ul> < ...

The function '.save' is not recognized by Mongoose

As a newcomer, I have been trying to understand the code in this calendar app that I created using express-generator. Everything seems to be working fine with connecting to MongoDB, but I am facing issues when trying to save a document. The section of my ...

Update the appearance of a cell if the value within it is equal to zero

I have discovered a way to achieve this using inputs. input[value="0"] { background-color:#F7ECEC; color:#f00;} Now, I am looking for assistance in applying the same concept to table cells. Can anyone provide guidance? Thank you. ...

Encountering difficulties when attempting to upload to Google Cloud using a signed URL

Seeking help to troubleshoot why the video upload is not working as expected. I am able to successfully connect to my bucket using a signedURL, but when trying to upload the video, it's not functioning properly. const submitVideo = async () => { ...

Having trouble accessing the `then` property of undefined while utilizing Promise.all()?

An issue has occurred where the property 'then' of undefined cannot be read: getAll(id).then((resp) => {...} ... export function getAll(id){ all([getOne(id), getTwo(id)]); } ... export all(){ return Promise.all([...arg]) } I' ...

Issue with formik onchange event not filling data in Material UI TEXTFIELD component

Greetings! I am currently working on a React project where I am managing the authentication process. I am using Material UI and Formik for validation and handling input changes. However, I encountered an issue with my onchange Formik handler in the TEXTF ...

Having trouble with Socket.io and its io.emit() method refusing to work? If communication from server to client isn't going smoothly, you may need a solution for sending data from the server to

My latest project is a document converter program that utilizes LibreOffice to convert documents to PDF format. Here's my server running on localhost:3000 import express from "express"; import bodyParser from "body-parser"; import ...

Angular JS form cloning feature

I'm facing a challenge in creating a dynamic form with multiple sections. At the end of the form, I want to include a "Add New Form" button which will duplicate the existing form below it, each with its own save button. What's the most effective ...

Tally the values entered into the text input field

I am interested in counting the number of IDs within an input of type "text" The values return like this: 1, 4, 6, etc. <input type="hidden" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" /> ...

Show all column data when a row or checkbox is selected in a Material-UI datatable

I am currently working with a MUI datatable where the properties are set as below: data={serialsList || []} columns={columns} options={{ ...muiDataTableCommonOptions(), download: false, expa ...

The hunt is on for greater value within the index

My requirement is to check the text content of a box. If it matches any value stored in an ARRAY, then I have to execute a specific action. var ARRAY1 = ["Saab", "Volvo", "BMW"]; if (select[i].innerHTML.indexOf('ARRAY1') != -1){//code here} ...

executing ajax request to call a function, encountering partial success and encountering partial failure

Apologies for the lack of clarity in the title. I currently have a search engine that utilizes an ajax function. At present, when I type "t" in the search box, only the tags containing the word "t" are displayed (for example, if I type "t", then "test" sho ...

What are the best ways to create image animations on top of other images using CSS or JavaScript?

Imagine if the first image is in black and white, while the second one is colored. How can we make the black and white image change to color after a timeout period, with an animation similar to loading progress bars? Is this achievable using CSS or JavaScr ...

"The website seems to be experiencing some technical difficulties on Firefox, but I have switched to

I attempted to reset the text area after sending a message with the code below: $(document).keypress(function (e) { if (e.which == 13) { e.preventDefault(); var $form = $('#f1'); $.ajax({ url: $form.attr( ...

Utilize React Hook Form to easily reset the value of an MUI Select component

I created a dropdown menu where users can select from "Item 1", "Item 2", and "Item 3". Additionally, there is a "Reset" button that allows users to clear their selection and make a new one. Below is the code I used: import React from ...

JavaScript CompleteLink message

Hey there, I've come across a JavaScript code for a countdown timer but need some assistance with it. The issue I'm facing is that within the code, there's a line that displays a message to the user when the timer reaches zero. I want to kn ...

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. Is the ...

"Interactive" - Utilizing javascript and html5 to create engaging game animations

Imagine I have a base class that looks like this: function Tile(obj) { //lots of default variables such as colors and opacity here } Tile.prototype.Draw = function () { ctx.fillStyle = "rgba(" + this.Red + "," + this.Green + "," + this.Blue + "," ...

Switch up the appearance of a document by manipulating the stylesheet using a select tag

I'm currently facing an issue with the implementation of a drop-down box on my website for selecting different themes. Despite having the necessary javascript code, I am unable to get it working correctly. Here's the snippet: //selecting the sele ...

unable to use ref to scroll to bottom

Can someone explain to me why the scroll to bottom feature using ref is not functioning properly in my code below? class myComponent extends Component { componentDidMount() { console.log('test') // it did triggered this.cont ...