Function that recursively checks for the existence of an ID within a nested object structure

I need assistance in developing a function that can determine whether the link ID of an object or any of its children match a specific ID. For instance, if the link ID for Product paths is 51125095, the function should return true when this ID is passed into it.

Below is a sample object:

const sampleObj = {
  id: '55259494',
  menuText: 'Top level link',
  link: {
    id: '55259472',
    slug: 'lop-level-link',
  },
  children: [
    {
      id: '53664310',
      menuText: 'Product paths',
      link: {
        id: '51125095',
        slug: 'product-paths',
      },
      children: [],
    },
    {
      id: '53664355',
      menuText: 'Testing',
      link: {
        id: '51272081',
        slug: 'testing',
      },
      children: [],
    },
    {
      id: '53664382',
      menuText: 'Relay',
      link: {
        id: '51489535',
        slug: 'relay',
      },
      children: [],
    },
    {
      id: '55259577',
      menuText: 'About us',
      link: {
        id: '55259487',
        slug: 'about-us',
      },
      children: [],
    },
  ],
}

The initial implementation of the function is as follows:

const isObject = (value) => {
  return !!(value && typeof value === 'object' && !Array.isArray(value))
}

const containsActiveLink = (linkObject = {}, pageIDToMatch) => {
  if (isObject(linkObject)) {
    console.log('Run:' + linkObject.menuText)
    console.log(linkObject)
    if (linkObject.link.id === pageIDToMatch) {
      return true
    }

    if (linkObject.children.length > 0) {
      linkObject.children.map((child) => containsActiveLink(child, pageIDToMatch))
    }
  }
  return false
}

const isActiveLink = containsActiveLink(sampleObj, '51125095')

Your support with refining this function would be highly appreciated. Thank you!

Answer №1

Although not the most efficient way as it scans the entire object, this code snippet provides a good starting point for searching.

const sampleObj={id:"55259494",menuText:"Top level link",link:{id:"55259472",slug:"lop-level-link"},children:[{id:"53664310",menuText:"Product paths",link:{id:"51125095",slug:"product-paths"},children:[]},{id:"53664355",menuText:"Testing",link:{id:"51272081",slug:"testing"},children:[]},{id:"53664382",menuText:"Relay",link:{id:"51489535",slug:"relay"},children:[]},{id:"55259577",menuText:"About us",link:{id:"55259487",slug:"about-us"},children:[]},]}

function find_id(data, id) {

  var found = false

  const iterate = (obj) => {
    if (!obj) {
      return;
    }
    Object.keys(obj).forEach(key => {
      var value = obj[key]
      if (key == 'id' && value == id) {
        found = true;
      }
      if (typeof value === "object" && value !== null) {
        iterate(value)
      }
    })
  }

  iterate(data)
  return found;
}
console.log(find_id(sampleObj, "55259577"))

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 is the best way to secure the installation of python packages for long-term use while executing my code within a python shell on NodeJS?

I have been encountering difficulties while attempting to install modules such as cv2 and numpy. Although I have come across a few solutions, each time the shell is used the installation process occurs again, resulting in increased response times. Below i ...

The "if" statement carries out the identical action each time it is executed

Despite my efforts to toggle the value of the turn variable every time the if statement runs, I keep encountering the same outcome. It appears that turn consistently evaluates as 2. Below is the code snippet in question: $(function() { var turn = 2; ...

Error encountered in MySQL and NodeJS: Unable to add new query after invoking quit with transactions

While working on implementing MySQL for NodeJS and Restify, I encountered a flawless experience with queries. However, when attempting to utilize data updating functionality through transactions, I faced the error message: Error: Cannot enqueue Query after ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Unable to properly load the Kendo Tree View based on the selected option from the combo box in the Kendo UI framework

I am encountering an issue where the Kendo treeview is not populating with different values based on a selection from the Kendo combo box. I have created a JSFiddle to showcase this problem. http://jsfiddle.net/UniqueID123/sample In the scenario provided ...

Displaying JSON data in a browser using Node.js without the need for refreshing the page

I am currently working on a node.js server that fetches JSON data from an external source and displays it in a browser window. I need assistance in setting up an automatic update every minute to reflect any changes in the JSON without requiring a manual re ...

How to assign attributes to all child elements in Angular?

I have a unique component in Angular that I utilize throughout my app. It's a button component which I use by calling <app-delete-btn></app-delete-btn> wherever needed. I tried to set the tabindex="1" attribute for my component ...

Having trouble getting the convert-multiple-files npm package to function properly on an Elastic Beanstalk environment running Amazon Linux

Following a successful deployment, I encountered an issue with my file conversion script when attempting to convert files as outlined in the documentation. The script works flawlessly on both a local Windows 10 machine and Ubuntu 20.04 LTS. const { conv ...

Expansive menu that stretches the full height of the webpage

I'm having difficulty making my side spry menu extend the full length of the webpage. I tried using this code: $("nav").css({ "height" : $("nav").height() }); but it still isn't working as expected. I just want the grey color, like ...

Is there a way to ensure my Vue variable is declared once the page has fully loaded?

I have implemented a v-for loop in my code: <div v-for="(user, index) in users" :key="index" :presence="user.presence" class="person"> <span class="cardName h4">{{ user.name }}</span> ...

Creating an Angular table with dynamic column headers

While working on an angular app to showcase data from different sources, I set up a JSON file with a list of various data sources along with their respective values. Here's an example: var configurableConfigurations=[ { name:"Locations", ...

How can you trigger an event when a table cell is selected and a key is pressed?

In my project, I have some td elements with a class name assigned to them. My goal is to trigger a pop-up window when one of these td elements is in focus and the F9 key is pressed. Here's what I've attempted so far: $(document.body).keypress(fu ...

Querying and Retrieving a List of Nested Documents in MongoDB

I have multiple solutions, each of which may contain various projects. To represent this relationship, I opted for embedding the projects within the solution document. For example: [{ _id: "1", solutionTitle: "Some Sample Solution", p ...

Incorporate a division based on the selection made from a jQuery dropdown menu

Is there a way to dynamically display a div to the right of a drop-down menu based on the user's selection using DOM manipulation? For reference, you can view an example of my current progress here: http://jsbin.com/#/afojid/1/edit The initial drop ...

Is it possible to add my own designs to a three.js model?

I am looking to add some personal touches to my three.js model by drawing on it in the scene. How can I achieve this effect of 'graffiti' on my models within the scene? ...

Mobile device scrolling glitch

I'm currently working on my website, which can be found at . After testing it on mobile devices, I came across an issue that I just can't seem to fix. For instance, when viewing the site on a device with 768px width, you can scroll to the righ ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

Stop the jQuery custom slide animation when there are no more items to display

I have designed a unique slider for users to view the work process https://i.sstatic.net/FLYne.png When a user clicks the button, the slider will move left or right depending on the button clicked. However, if the user clicks multiple times, the slider ma ...

Updating the src of an iframe and adding an onclick event to a link using JavaScript

Looking to design a page that accommodates both login and sign up functionalities by dynamically updating the src of an iframe. In the navigation bar, there is: <li id="change"><a onclick="sign()">Sign up</a></li> And within the ...

Using TypeScript arrow function parentheses in the filter function

If I have an array of movie objects like this: const movies: Movie[] = [ movie1, movie2, movie3, movie4 ]; And if I want to remove a specific movie from the array, such as movie2, I can use the following code: movies = movies.filter( m => m !== ...