Retrieving the JSON parent data for the specified node

I appreciate all the feedback on my first question. I will give it another shot.

Here is a JSON object example:

var obj =     {  
       "data":[  
          {  
             "data":{  
                "title":"title1",
                "attr":{  
                   "id":111
                }
             },
             "children":[  
                {  
                   "data":{  
                      "title":"title2",
                      "attr":{  
                         "id":222
                      }
                   },
                   "children":[  
                      {  
                         "data":{  
                            "title":"title3",
                            "attr":{  
                               "id":333
                            }
                         }
                      }
                   ]
                },
                {  
                   "data":{  
                      "title":"title4",
                      "attr":{  
                         "id":444
                      }
                   },
                   "children":[  
                      {  
                         "data":{  
                            "title":"title5",
                            "attr":{  
                               "id":555
                            }
                         }
                      }
                   ]
                }
             ]
          }
       ]
    };

I am seeking assistance in tracing a "lineage" to a specific id value through the title properties. For example, if given 222, the expected result is title 1; for id 333, title1 > title 2; and for id 555, title1 > title 4. Note that these are siblings of parents rather than direct parents.

This is what I have attempted so far:

var x = 555;

var path = "";
function search(path, obj, target) {
    for (var k in obj) {
        if (obj[k] === target) {
            return path + "['" + k + "']"
        }
        else if (typeof obj[k] === "object") {                      
            var result = search(path + "['" + [k] + "']", obj[k], target);
            if (result)
                return result;
        }
    }
    return false;
}

var path = search(path, obj, x);
console.log(path); // "['data']['0']['children']['1']['children']['0']['data']['attr']['id']"

However, I have been unable to retrieve the title attributes. Any help would be appreciated. Thank you for your patience!

Answer №1

One way to locate a specific item using loops is as follows:

var obj={"data":[{"data":{"title":"example1","attr":{"id":111}},"children":[{"data":{"title":"example2","attr":{"id":222}},"children":[{"data":{"title":"example3","attr":{"id":333}},"children":[{"data":{"title":"example4","attr":{"id":444}},"children":[{"data":{"title":"example5","attr":{"id":555}},"children":[]}]}]}]}]}]}

var current = obj.data[0], titles = [];

while(current.data && current.data.attr.id != 444){
titles.push(current.data.title);
current = current.children[0] || {}
}

document.write(titles.join(" > "));

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

Trouble with parsing JSON in NodeJs

I have a JSON file containing the names of people that are stored. Using the Node Manager's filesystem, I read the content from this file and attempt to convert the JSON to a string and then parse it into a JavaScript object. However, after parsing it ...

using the useEffect hook to create a loop that runs infinitely

For my project, I am working on updating data in firebase. The issue that I'm facing is that the data seems to be constantly looping, causing potential crashes. Is there a way to stop this loop and prevent any crashing? import "./App.css"; ...

Creating attributed strings with text for image encoding

When it comes to inserting images into a TextKit textView using Swift, I rely on NSMutableAttributedString and NSAttachment with the imagePickerController code below: func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithIn ...

Customize the size of innerWidth and innerHeight in your THREEjs project

Is there a way to customize the size of the window where this function launches instead of it automatically calculating the height and width? I've attempted to modify this section of the code, but haven't had any success so far: renderer.setSiz ...

Identify the descendant of the `<li>` tag

I need help creating a interactive checklist. The idea is that when you click on an item in the list, a hidden child element should become visible. <div id="list_one"> <h2>LIST TITLE</h2> <div id="line"></div> < ...

Converting JSON into object representation with modified name field

I am facing a challenge with deserializing this JSON data: { "name": { "field": "kop", "field2": false } } The issue is that the key "Name" keeps changing. How can I handle this situation? For instance, i ...

Guide to accessing the content within an h1 tag with JavaScript

I currently have a setup with 3 pages: 2 of them are WordPress pages while the other page is a custom page template featuring a form. The first two pages were created using the wp-job manager plugin. The first page includes a dropdown menu with a list of a ...

Rails: Ensure that JSON form fields remain populated in case the form encounters a validation error

I am using a rails simple form to create a product with three fields inside in order to associate it with appropriate categories: <div class="form-group"> <%= f.input :child_category_id, :collection => @categories.order(:name), :l ...

Tips for transferring a variable between routes in express-js

Currently, I am using npm disco-oauth to authenticate with Discord. After authenticating in the main app.js file, I store the userKey in a cookie using cookie-parser. This allows me to access user information and the guilds that the user is a part of. Howe ...

Updating the web browser does not display the changes made on the page

Currently diving into the world of Angular and I've successfully cloned the repository. After installing the dependencies using npm, I have the web server up and running smoothly. Accessing the page on localhost:4000 works like a charm. Interestingly ...

Utilize jQuery and PHP to populate an HTML Select Field with data retrieved from a MySQL Database in JSON format

I am exploring how to Transfer Database Data into an HTML Dropdown Selection Field using jQuery. I came across a useful example that seems promising. Although I am new to jQuery and JavaScript, I am eager to learn. My goal is similar to the approach descr ...

Can dynamic variables be incorporated within a const?

Could dynamic variables be used in the code below? const [viewport, setViewport] = useState ({ latitude:-8.683895, longitude:115.152307, width:800, height:440, zoom:16 }); I want the latitude and longitude to be flexible, like this: co ...

Is it incorrect to append an array to a ul block using jQuery?

I am encountering an issue when trying to append an array to HTML. The array consists of HTML elements, starting with "li", then "img", and ending with "/li". When I try to append the array, it returns: <li></li> <img src="..."> Howeve ...

Tips for adjusting the size of Material UI icons

My Material UI icon size doesn't align naturally with the button: https://i.sstatic.net/l1G98.jpg Button code snippet: <Button variant="outlined" startIcon={<FacebookIcon />}> </Button> Here is the complete example ...

Retrieve picture from mySQL database and display it in a listview on an Android

Looking to display an image along with text in a listview fetched from a MySQL database. Here is the code snippet: public void fetchDoctors(){ String url_select = "http://10.0.2.2/BloodGlucose/selectDoctor.php"; HttpClient ...

Is there any method to avoid the hassle of constantly adjusting margins and paddings on my one-page website?

One issue I encountered was that the buttons weren't scrolling me to the top of the anchor, instead scrolling too far into the section due to the fixed navbar overlapping. I tried solving it with margins and paddings but believe there must be a simpl ...

The query attribute of the http_incomingmessage in Node.js is not empty, causing Express to have trouble parsing the query parameter

While utilizing node version 6.9.4 and express version 4, there seems to be an issue with the creation of the IncomingMessage object in _http_common.js. Specifically, on line number 60, the parser.incoming.query function is being set to a value (usually it ...

Is it possible to translate the IIFE functions of threejs into ES6 format?

I'm currently facing a challenge in breaking down my threejs project into smaller modules. One specific function that I'm struggling with is the following: var updateCamera = (function() { var euler = new THREE.Euler( 0, 0, 0, 'YXZ&apos ...

Interactive loading of datalist choices using AJAX in the Firefox browser

I have recently decided to replace the Jquery UI autocomplete function on my website with HTML5 datalists that load dynamic options. After researching this topic extensively, I came across various answers on Stack Overflow, such as How do you refresh an HT ...

Is there a way to showcase the data from the .json file using the jquery library?

I have a .json file on the server containing data that I want to display on my webpage. Unfortunately, I'm not very familiar with JavaScript syntax, so I'm having some trouble. My goal is to show just one specific parameter from the file, but fo ...