Discover data using JavaScript recursively through paths

Here is the data structure I am working with:

[
  {
    name: 'root',
    children: [
      {
        name: 'page',
        children: [
          // and so on
        ]
      }
    ]
  }
]

I am in need of a function that can retrieve the latest object based on a specified path. For example, calling getCurrentTree('root.page') should return

      {
        name: 'page',
        children: [
          // and so on
        ]
      }

I hope my explanation is clear! Recursion tends to be challenging for me, so any help is appreciated. Should I use find, filter, or maybe even reduce? If you have any clever ideas, please share!

Thanks a lot

Answer №1

One method involves verifying the name and searching through the children, while another option is to simply return the object.

function navigateTree(array, names) {
    var [name, path] = names.split('.', 2),
        result;

    array.some(o => {
        if (o.name === name) {
            return result = path ? navigateTree(o.children, path) : o;
        }
    });
    return result
}

var data = [{ name: 'root', children: [{ name: 'page', children: [] }] }];

console.log(navigateTree(data, 'root.page'));

Answer №2

Is this something you are looking for?

let mainList = [
  {
    name: 'root',
    children: [
      {
        name: 'page',
        children: [

        ]
      }
    ]
  }
]

function getSpecificBranch(path) {
  const paths = path.split('.')
  return navigate(mainList, paths, 0) 
}

function navigate(list, paths, level) {
  const node = list.find(obj => obj.name === paths[level])

  if (level === paths.length - 1) {
    return node
  } else {
    return navigate(node.children, paths, level + 1)
  }
}

getSpecificBranch("root.page")
// => {name: "page", children: Array(0)}

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

I'm puzzled as to why my createDoorMethod is returning a string value instead of a number, even though I am passing it a number. Can someone help me

Currently enrolled in a web development course, I am diving into the world of Angular 2 and TypeScript. Despite following along with the video tutorial and using the same code, my implementation is not working as expected, leaving me puzzled. Here is the ...

Are you in the business of building JavaScript hubs?

I have a unique setup where my express server is in charge of handling all routing and session functionalities. I've envisioned a system where logged-in users can connect to distinct "hubs" based on the location of each hub. My idea was to treat each ...

Mongodb processes timestamp data in a long format

I'm curious about how to work with timestamps in MongoDB using NumberLong in our database. Which JavaScript function should I use in the MongoDB shell for this purpose? For instance, how can I determine the millisecond time of the next day after a ce ...

Adjusting the dimensions of the central container

Does anyone have suggestions on how to resize the middle red container when the window is resized, considering the fixed-width black containers on the left and right? I am aware that this can be achieved using jQuery by calculating the window width and a ...

The ViewChild from NgbModalModule in @ng-bootstrap/ng-bootstrap for Angular 6 is causing the modal to return as

I have successfully integrated ng bootstrap into my project, specifically utilizing the modal module to display a contact form. The form includes input fields for email and message, as well as a submit button. You can find the ngbootstrap module I am using ...

What is the best way to resize an element such as an image?

When an image is resized using a percentage, it preserves its aspect ratio properly. I am looking for a way to replicate this behavior with a div. My current challenge involves precisely positioning an element relative to an image. The image fills 100% of ...

Creating separate files for establishing DB connection and writing Node.js queries is a recommended practice for organization

Having an issue with connecting dbconnection.js and demo_api_select.js. When trying to declare a variable in demo_api_select.js, I am encountering errors like this: Error Notification Please assist me in resolving this problem. dbconnection.js: var ...

Eliminating memory leaks in a React web application

I'm facing an issue in my ReactJS web application with the following code: useEffect(() => { const fetchInfo = async () => { const res = await fetch(`${api}&page=${page}`); setLoading(true); try { const x = awa ...

Exploring the transition from JavaScript to jQuery

Currently, I have set up an ajax request in combination with JavaScript to fetch data from an external file. The code looks like this: const ajaxRequest = new XMLHttpRequest(); const handleResponse = function() { if (ajaxRequest.readyState === 4) { ...

Discovering objects on a JavaScript webpage using Selenium

Looking to automate some searches for myself, but running into an issue. Here is the website in question: Struggling to locate the search bar using the program, and unsure why. driver = webdriver.Firefox() driver.get('https://shop.orgatop.de/') ...

What exactly is the function of the NextPage feature in Next.js?

Recently, I began incorporating TypeScript into my Next project. Could someone clarify the purpose of the following code snippets for me? import { NextPage } from 'next'; export const Page: NextPage = () => {} After reviewing the documentation ...

Refresh the navigation bar on vuejs post-login

Creating a client login using Vue has been a challenge for me. My main component includes the navigation bar and the content rendering component. The navigation component checks if the user is logged in to display the buttons for guests and hide the button ...

What is the best way to determine which watchers are triggered in Vue.js?

Within my parent component, there are numerous nested child components. Whenever a click occurs on one of the child components, it triggers an update to the route. The parent component watches the route property and performs certain actions when it change ...

Issue: Unable to find a compatible version of chokidar. Attempted chokidar@2 and chokidar@3 after updating npm to version 7.*.*

After using ejected CRA, it compiled successfully but then broke with the following error. The issue started to occur after updating npm from version 6 to 7. You can now view webrms in the browser. Local: http://localhost:3001 On Your Netw ...

"Encountering a 405 error when transmitting information from an HTML file to a Python Flask server using 'GET / HTTP/1.1'

As someone who is brand new to the world of python and AJAX, I have been piecing everything together from various sources online including examples and Flask documentation. So far, I have managed to make some progress. My goal is to send latitude and longi ...

Using the Match() function with an array of objects

I am working with an object array containing multiple variables. let Novels = []; class Novel { constructor(isbn, title, author, edition, publication, year) { this.isbn = isbn; this.title = title; this.author = author; this.publicat ...

Return to the previous page with different query parameters, not the same one

When it comes to reverting state location back by 1 step in Angular, we can utilize something along the lines of this.location.back();. This method works well unless the system redirects to the same URL but with different query parameters. In such cases, ...

Accurate date and time depiction at a high resolution using JSON and JavaScript

Is there a standardized method for displaying high-resolution timestamps in JSON and/or JavaScript? It would be ideal to have support for at least 100 ns resolution, as it would simplify the server code (due to the 100 ns resolution of the .NET ...

Create a regulation that permits access solely to individuals currently logged into the system database

I am a beginner when it comes to working with Firebase and its rules. My goal is to implement a system where each user in the Firestore database has a boolean field called isOnline, as shown in the image I have attached. https://i.stack.imgur.com/7M3dc.pn ...

I encountered an issue while attempting to connect to my MySQL database using my Express API endpoint: error message "connect ECONNREFUSED 127.0

I am currently in the process of developing a web application for a bootcamp using Express and MySQL. I have set up a route to handle a GET request to an endpoint which is supposed to query my MySQL database table and retrieve all records. My intention is ...