Discover a specific item using its id within Javascript

Let's talk about my unique tree structure:

{
    "id": 0,
    "parentId": null,
    "name": "Tech Company",
    "children": [
        {
            "id": 1235,
            "parentId": 0,
            "name": "Software Development",
            "children": [
                {
                    "id": 3333,
                    "parentId": 154,
                    "name": "Web Development",
                    "children": [],
                    "companies": [
                        {
                            "id": 348,
                            "name": "Google"

                        },
                        {
                            "id": 30,
                            "name": "Microsoft"
                        }
                    ]
                },
                {
                    "id": 319291392,
                    "parentId": 318767104,
                    "name": "Mobile App Development",
                    "children": [],
                    "companies": [
                        {
                            "id": 353,
                            "name": "Apple"
                        },
                        {
                            "id": 19,
                            "name": "Samsung"
                        }
                    ]
                }
            ],
            "companies": [
                {
                    "id": 35715,
                    "name": "Amazon"
                },
                {
                    "id": 85,
                    "name": "Facebook"
                }
            ]
        }
    ]
}

I am on a mission to locate objects by their specific ids. For example, if I'm in search of an object with id:353, I would retrieve:

{"id": 353,"name": "Apple"} 

If I need to find an object with id:1235, the output should be:

{"id": 1235,"name": "Software Development"}

Despite numerous attempts, the intricate nature of this tree makes it challenging for me to accomplish my goal.

Answer №1

function searchId(obj, id) {
    if (obj.id == id) {
        return obj;
    }
    if (obj.children) {
        for (var i = 0; i < obj.children.length; i++) {
            var result = searchId(obj.children[i], id);
            if (result) {
                return result;
            }
        }
    }
    if (obj.merchants) {
        for (i = 0; i < obj.merchants.length; i++) {
            result = searchId(obj.merchants[i], id);
            if (result) {
                return result;
            }
        }
    }
    return false;
}

Answer №2

Source:

Retrieve an array of objects based on key, value, or key and value matches

function findObjects(obj, key, val) {
    var results = [];
    for (var prop in obj) {
        if (!obj.hasOwnProperty(prop)) continue;
        if (typeof obj[prop] === 'object') {
            results = results.concat(findObjects(obj[prop], key, val));    
        } else 
        //check for matching key and value pair
        if (prop == key && obj[prop] == val || prop == key && val == '') { //
            results.push(obj);
        } else if (obj[prop] == val && key == ''){
            //add object only if it's not already included
            if (results.lastIndexOf(obj) == -1){
                results.push(obj);
            }
        }
    }
    return results;
}

Retrieve an array of values that match a specific key

function findValues(obj, key) {
    var results = [];
    for (var prop in obj) {
        if (!obj.hasOwnProperty(prop)) continue;
        if (typeof obj[prop] === 'object') {
            results = results.concat(findValues(obj[prop], key));
        } else if (prop == key) {
            results.push(obj[prop]);
        }
    }
    return results;
}

Retrieve an array of keys that correspond to a certain value

function findKeys(obj, val) {
    var results = [];
    for (var prop in obj) {
        if (!obj.hasOwnProperty(prop)) continue;
        if (typeof obj[prop] === 'object') {
            results = results.concat(findKeys(obj[prop], val));
        } else if (obj[prop] == val) {
            results.push(prop);
        }
    }
    return results;
}

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 middleware with express in the proper manner

Hello there! I'm just double-checking to see if I am using the correct method for implementing middleware in my simple express app. Specifically, I am trying to ensure that the email entered during registration is unique. Here's an example of wha ...

How can I use office.js to access specific cell formats in Excel?

Currently, I am delving into the new office js API to transition existing Excel add-ins to utilize this innovative technology. While it is simple to fetch an array of values from a complete range by queuing a single load on the context, obtaining cell for ...

What are some strategies for handling data after it has been retrieved using Axios?

In my current project, I am working with MySQL database and fetching data using Axios and a useEffect hook. Once the data is retrieved, I pass it to a component as a prop. Here's how: const Component = () => { //Database URL const urlProxy = &q ...

Error: Issue transferring data to controller from Ng-Style

Currently, I am developing an application using Ionic and AngularJS. In this project, I am using ng-repeat to populate the results and want to display different colors based on certain criteria. Initially, I managed to achieve this using inline ng-style c ...

Using JavaScript to Show Variables When Clicked

I have been working on populating multiple divs with data stored in variables that change when an image is clicked. Here's a snippet of the code within my tag:</p> <pre><code>function displayName(name){ document.getElementById( ...

Use jQuery to open and close HTML tags efficiently

It seems like the task I have at hand may not be as simple as I had hoped, so here I am seeking some reassurance. I am aiming to switch out an image with a closing div, then the image itself, followed by another opening div. Let me illustrate this with a ...

The req.body in Express.js appears to be empty when utilizing form-data

snapshot of postman When I send data using form-data in my Express.js application, req.body appears to be empty. However, if I send the data using raw JSON, the expected object is present in req.body. Below is how my setup looks: Here is my index.js file ...

Acquire data from an HTML Element

I was provided with the following div that was already created for me: <div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1 ...

Bidirectional Data Binding in AngularJS

In my angular application, there is a dropdown with various values. When a user selects a specific value from the dropdown, I want to display the complete array corresponding to that value. <!doctype html> <html lang="en"> <head> < ...

What is the reason behind my button appearing beneath my links in React?

https://i.sstatic.net/Qmm4z.jpg Here is an image showcasing the current header render. The header consists of a HeaderMenu and 3 Links. While the links are functioning properly, the HeaderMenu is causing the links to be positioned below it. The HeaderMenu ...

Angular: The dilemma of choosing between updating individual properties or reassigning objects

I am currently working with an object structure that looks like this: steps:any = [ { id: 1, name: "A", next: [{ id: 2, name: "B" }, { id: 3, name: "C" }] }, { id: 2, name: "B", next: [{ id: 1, name: "B" }] }, { ...

Utilizing innerHTML in JavaScript along with an if/else statement for controlling a dropdown menu in Bootstrap 4

My project is almost complete, but I'm struggling to include innerHTML statements when a user fails to select an item from the two dropdown menus. While I know how to achieve this using alerts, I want the message to be displayed on the page itself if ...

Is there a way to set up HTML5 Video.js in Boonex Dolphin?

My current project involves utilizing the Video.js Source Code to update the video player on my website that currently uses Boonex Dolphin. I am looking to transition from the flash player used by Dolphin to HTML5. Dolphin's modules contain specific f ...

How can I display all values in Meteor Blaze by iterating through a mongo cursor?

Can someone please guide me in the right direction? I have an application that uploads a CSV file to MongoDB and then displays it within the Meteor framework. I am facing an issue where I am subscribing to the data in the Template.onCreated function, but I ...

Angular 6 is experiencing an issue with the functionality of the file toggle JS

Currently, I am utilizing the file toggle.js within the Urban theme. In the HTML chatbox, using the img, the file toggle.js is hardcoded and is functioning properly. However, when implementing code in Angular 6, the toggle.js is not functioning as expecte ...

Validation of the length for masked input fields

Below is an example of a masked field: <input id="phone1" placeholder="(___) ___-____"/> The masking is achieved using the code snippet below: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jq ...

Establishing a connection to MongoDB using JavaScript

Currently, I'm working on a fun little project revolving around a web calendar. For this project, I've decided to integrate mongoDB into it. Fortunately, I have successfully configured MongoDB and established a connection with PHP. However, I am ...

Updating object values within a while loop using JavaScript

I am facing an issue with managing an array of JavaScript objects that have a property 'table' with values table1, table2, table3, or table4. Each table should only accommodate 6 members. I have implemented a while loop to check if 'table1&a ...

How can curly braces be utilized in an array reduce method?

If the function `fn3` is used instead of `fn2` in this code snippet running on node 9.5.0, the `console.log(totalUpvotes)` will display `undefined`. Shouldn't it actually be equal to 92? const posts = [{id: 1, upVotes: 2}, {id:2, upVotes: 89}, {id: ...

Utilizing Boolean Operators in JavaScript with Thymeleaf: A Guide

When incorporating Boolean conditions in JavaScript with Thymeleaf using th:inline="javascript", an exception is thrown which appears as follows: org.xml.sax.SAXParseException; lineNumber: 14; columnNumber: 22; The entity name must immediately follow the ...