Obtaining a numerical value that signifies the depth of an object or nested object within an overarching object

Looking at this JavaScript object

var items = [{
    content: 'A_lvl0',
}, {
    content: 'B_lvl0',
}, {
    content: 'C_lvl0',
    children: [{
        content: 'C_1_lvl1',
    }, {
        content: 'C_2_lvl1',
        children: [{
            content: 'C_1_lvl2'
        }, {
            content: 'C_2_lvl2',
            children:[{
                content: 'C_1_lvl3'
            }, {
                content: 'C_2_lvl3'
            }]
        }]
    }, {
        content: 'C_3_lvl1'
    }]
}];

The "lvlx" in the content property of each object indicates how deeply nested it is. If we need to determine the nesting level of a specific object within this structure using recursion, we might encounter challenges in keeping track of the top level.

We have a function that can print out all nested contents of objects:

var scanObj = function (obj) {
    for (var i = 0; i < obj.length; i++) {
        console.log(obj[i].content);
        if (obj[i].hasOwnProperty('children')) {
            scanObj(obj[i].children);
        }
    }
};

Now we are trying to create functions like:

var getlvlByRef = function (obj,subobject) {
       //return lvl
    };




var getlvlByPropertyValue = function (obj,propertyname,propertyvalue) {
       //return lvl
    };

The challenge lies in determining the correct approach to keep track of the depth when reaching the innermost nested levels. Any guidance on this would be greatly appreciated.

You can also check out the code snippet on this fiddle http://jsfiddle.net/eG3qR/

Answer №1

Check out the fiddle I created to see my solution in action:

http://jsfiddle.net/3W5qY/3/

function findLevelByProperty(obj, propertyName, propertyValue, level){    
    if(level === undefined) level = 0;
    if(obj === undefined || obj.length === 0) return -1;
    for(let i = 0; i < obj.length; i++){
        let curObj = obj[i];        
        if(curObj[propertyName] !== undefined && curObj[propertyName] === propertyValue) {
            return level;}        
        if(curObj["children"] !== undefined){
            let childSearchResult = findLevelByProperty(curObj["children"], propertyName, propertyValue, ++level);
            if(childSearchResult > 0) {                
                return childSearchResult;
            }
        }
    }
    return -1;
}

If the property is not found, the function will return -1.

Answer №2

If you wish to have scanObj display the current level you are on, you can simply pass the level parameter down to scanObj.

Here is a possible implementation:

const scanObj = function (obj, level) {
    if (level === undefined) {
      level = 0;
    }

    for (let i = 0; i < obj.length; i++) {
        console.log(obj[i].content);
        console.log(level);

        if (obj[i].hasOwnProperty('children')) {
            scanObj(obj[i].children, level);
        }
    }
};

scanObj(myObj, 0);

This code can potentially be refactored to eliminate the need for the "init" flag. Overall, it will output both the object's content and its corresponding level in the hierarchy.

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

Activate the "order evaluation" trigger on the checkout page in Woocommerce

I have implemented the Woocommerce Advanced Shipping plugin created by Jeroen Sormani for managing shipping methods, along with the WooCommerce Pay for Payment plugin developed by Karolína Vyskočilová to add a fixed €5 fee to the "cash on delivery" pa ...

Efficiently managing desktop and mobile pages while implementing lazy loading in Angular

I am aiming to differentiate the desktop and mobile pages. The rationale is that the user experience flow for the desktop page involves "scrolling to section", while for the mobile page it entails "navigating to the next section." The issue at hand: Desk ...

Generating a tag next to an entry field using material-ui's TextField and getInputProps

In my project, I am utilizing a material-ui TextField to design an input alongside a label for a typeahead picker component using downshift. After exploring the demos, I have implemented the following code snippet: <FormControl fullWidth className={cl ...

Exploring the process of retrieving data from localStorage in Next.js 13

Having recently delved into the realm of Next JS, I've encountered a hurdle when it comes to creating middleware within Next. My aim is to retrieve data from local storage, but I keep hitting roadblocks. middleware.ts import { key, timeEncryptKey, to ...

Preserving text input with line breaks in a MERN Stack application

Can you help with saving multiple paragraphs in MongoDB? I have a textarea where users can input multiple paragraphs, but the line space is not being saved correctly in the database. Here is how I want the submitted data to look: Lorem ipsum dolor sit am ...

Initiating a click function for hyperlink navigation

Here is the HTML and JavaScript code that I am currently working with: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script> </head> <body> <a href="#f ...

Is it possible to trigger an event for only one connected client instead of broadcasting it to all clients using socket.io?

I am seeking a way to send an event to just one connected client, rather than broadcasting it to all clients using io.emit(). ...

Implementing Vue.js click event behavior on a component within the template

Encountering an issue while developing Vue's template onclick event. Trying to open a module when clicking a file, I have looked at some samples with native code, but it does not quite fit into my code and I cannot reach the console. Here is my code: ...

How can you switch the property of an object in VueJS?

I am currently working with an array called cars, which contains names of cars as well as a property called starred. My goal is to toggle the value of starred between true and false for each car, ensuring that only one car can have starred set to true at a ...

The Checkbox handler in Material-UI component fails to update the state - Version 5.0

Hey everyone, I'm facing an issue with my "Checkbox" component in React. After clicking on it, the state doesn't update to 'true' as expected. The checkbox works visually in the DOM but the state remains 'false'. Can someone p ...

Issues with finding your way

Whenever I am in the History.js file and click on a product list item to navigate to another page for more details and contact the seller, the issue arises. When I click on an item in History.js, nothing happens on that page. However, when I switch to Home ...

Disabling the ability to edit the rightmost portion of an input number field

I am looking for something similar to this: https://i.stack.imgur.com/ZMoNf.jpg In this case, the % sign will be shown in the input field by default and cannot be changed or removed. The user is only able to modify the number to the left of the % sign. P ...

The Vue feature responsible for displaying information on the webpage is currently not working as expected

I'm in the process of developing a settings page for a project. This particular page is based on HTML and utilizes JSON to store data, with Vue 3 being used to display the information on the page. However, I've encountered an issue where the data ...

I am looking to split an array into smaller subarrays, each containing 5 elements, and assign a distinct class to the elements within each subarray. How can I

I have a group of "n" "li" elements that I would like to split into "x" subsets using jQuery. Each subset should contain 5 "li" elements, and I also want to assign a different class to each subset. <ul> <li>text1</li> <li>text2&l ...

What steps need to be taken to set up Node.js to accommodate requests from external sources beyond just localhost?

After creating an application using NextJs, I successfully built it and ran it on a node server by executing 'npm run start' in Powershell. Everything works perfectly when accessing it locally through port 80. However, my Windows Server 2019 does ...

Change web page in JavaScript using post data

Is there a method to utilize JavaScript for navigating to a new URL while including POST parameters? I am aware that with GET requests, you can simply add a parameter string to the URL using window.location.replace(). Is there a way to achieve this with ...

Is it possible to extract a specific value from JSON data by making an AJAX call or applying a filter to the fetched JSON data?

I have been utilizing a treeview template and successfully displaying all the data. However, I am facing an issue where I need to pass a value from index.php to getdata.php. I attempted using an AJAX filter on the index.php page and also tried sending a v ...

Spinner loading - stays centered on screen even when scrolling up or down

<div id="Dvloading" style="float: left;"> <i id="loadingSpinner" class="icon-spinner icon-spin blue" style="margin-left: 50%; position:absolute ; margin-top: 25%; z-index: 1000; font-size: 800%;"></i> </div> This code displ ...

Stylus mistakenly fetches styl files from an incorrect directory

My issue involves a file named mobile.styl, which gathers all necessary styl files using the @import function: @import '../../common/styles/colors' @import '../../common/styles/init' @import 'landing' @import 'faq&apos ...

How can I uniquely combine a code with an existing CSS class and make modifications to it?

I am using ngx-skeleton-loader and I would like to change the color, but I am facing some difficulties. Here is an image that illustrates the issue. When looking at the developer tools, you can see the styles action in the styles action bar. .loader ...