How to Determine the Length of a Subarray in JavaScript

I am working with a JSON element that contains nested arrays:

json = [
        {
            "category": "Electronic",
            "param": "param1",
            "subMenu": [
                {
                    "subCategory": "Audio & Hifi",
                    "param": "param1-1",
                    "subMenu2": [
                        {
                            "type": "JVC",
                            "param": "param1-1-1"
                        },
                        {
                            "type": "Kennwood",
                            "param": "param1-1-2"
                        },
                        {
                            "type": "Sony",
                            "param": "param1-1-3"
                        },
                        {
                            "type": "Blaupunkt",
                            "param": "param1-1-4"
                        }
                    ]
                }]}]

I need to retrieve the length of the subarrays subMenu and subMenu2 for a specific function but have not found a suitable solution yet.

I have tried using a loop with

for (var i = 0; i < array.length; i++)
and
for (var i = 0; i < subMenu.length; i++)
but it did not give me the correct lengths. It was limited by the length of the main array.

You can see the issue in action here: https://jsfiddle.net/pp4t9nw2/4/

If anyone has a solution to this problem, I would greatly appreciate it.

Answer №1

If you want to nest loops within submenus, it's a good idea to use different variables for each loop. Here's an example:

for (var i = 0; i < json.length; i++) {
    for (var j = 0; j < json[i].subMenu.length; j++) {
        for (var k = 0; k < json[i].subMenu[j].subMenu2.length; k++) {
            let item = json[i].subMenu[j].subMenu2[k];
            // item.type available
        }
    }
}

Answer №2

If you're looking to find the number of elements in the main subMenu, you can access it by using json[0].subMenu.length.

Iterate through the json object (not an array as mentioned in your code) and for each element, you can retrieve its subMenu length by accessing json[iterator].subMenu.length.

To loop through subMenu2, you will need a nested loop using a different iterator variable to avoid conflicts.

Answer №3

When working with this scenario, it is important to correctly reference subMenu2. For instance: json.subMenu.subMenu2.length

However, it is worth noting that subMenu itself does not possess a length attribute, as it only contains subMenu2.

I trust this information has been beneficial to you.

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

Guide on Creating a Popup Window When the User's Cursor Moves Beyond the Webpage Boundary

Imagine you're browsing a webpage and as you move your mouse towards the "back" button, a window pops up within the webpage area, displaying important information. This is a clever way to grab the user's attention before they leave the website. B ...

"Utilizing JSON.net's SelectToken feature for data formatting

Looking at the XML provided below: <AgentBookingStatusResponse> <Eta>2012-11-19T15:40:15.0819269+00:00</Eta> </AgentBookingStatusResponse> After reading it into a JObject and converting it to a string using the code snippet belo ...

Exploring IP geolocation integration within Rails 3

I am looking to add a dynamic feature to my homepage that will display the location object closest to the reader's physical location. Currently, I have a Location model with longitude and latitude fields. My goal is to retrieve the location model obj ...

In what way does this closure cause componentDidUpdate to mimic the behavior of useEffect?

Recently, I came across an insightful article by Dan Abramov titled: A Complete Guide to useEffect. In the section that discusses how Each Render Has Its Own… Everything, two examples were provided. The first example demonstrates the usage of useEffect a ...

The issue with Jquery.Validate not functioning properly when trying to upload a file

I have integrated jQuery validation into my ASP.NET MVC project, and it is functioning correctly with textboxes. However, I am encountering an issue with file uploads. Below is the code snippet I am using: @model ffyazilim.Management.Model.Credential.Crea ...

Retrieving the URL of an image from a webpage's photo gallery utilizing the Facebook Graph API with the help of Javascript

After trying out multiple tutorials, it appears that the latest version of the Graph API has caused some issues with my code. Here is the snippet I am working with: function fetchAlbumImages(){ FB.api( '/760126260690750/photos&ap ...

Promises and Their Valuable Variables

Recently I began learning JavaScript and I'm encountering some confusion. Here's the code snippet that is causing me trouble: api.posts .browse({ limit: 5, include: 'tags,authors' }) .then(posts => { posts.forEach(post =&g ...

Learn how to dynamically insert input data into a table based on a specific ID in React JS!

[Help needed! I am trying to store the marks, id, and name values of each cell in objects of an array. However, I am not getting the correct answer. Can someone guide me on how to properly store the marks and id of each cell in objects of an array? const [ ...

Vue randomly sets the prototype of props in its definition

When the same code with the identical data structure is passed to the prop, it randomly sets the prop as an array or an object. The following is the code fragment: const props = defineProps({ all: { type: Array, default: [], } }) ...

Connecting Lavarel Pusher Socket in NUXT with SSR Mode

Looking to establish a connection between the Laravel Pusher Socket and NUTX.js (SSR Mode) Application. The code snippet above adds the socketio.js plugin file, but it seems to be causing some issues. Can anyone point out what might be going wrong? And ...

efficiency of this algorithm

function checkSubset(array1, array2) { const set1 = new Set(array1); const set2 = new Set(array2); for (const element of set2) { if (!set1.has(element)) { return false; } } return true; } Can we consid ...

In JavaScript, the addition and subtraction buttons may become disabled after nested lists are used

Recently, I embarked on a project to enhance the functionality of restaurant table items and implement value-saving features. Initially, everything worked smoothly with one item list. However, upon introducing a second list and attempting to manipulate it ...

Error: The document is unable to detect any input values

I've been struggling with this issue for quite some time now and I can't seem to figure it out, no matter how hard I try. It seems that my input field is not capturing the value entered by the user for some unknown reason. Let me share the code ...

Decoding JSON Data on Android (Utilizing Flickr API)

I have been trying to retrieve image URLs from the Flickr API for my Android app. Specifically, I am looking to extract the first owner and first id field from the JSON provided at the following link: http://pastebin.com/NVKXdELx My approach is as follo ...

Is there a method in TypeScript to make an enum more dynamic by parameterizing it?

I've defined this enum in our codebase. enum EventDesc { EVENT1 = 'event 1', EVENT2 = 'event 2', EVENT3 = 'event 3' } The backend has EVENT1, EVENT2, EVENT3 as event types. On the UI, we display event 1, event 2, a ...

Implement an AJAX link on the webpage using Yii framework

I'm currently working on developing a user interface for an application, and I've encountered an issue with my code that involves adding AJAX links using a Yii helper function. echo CHtml::ajaxLink('Link', array('getajaxlinks&apos ...

Utilizing Jackson's JsonTypeInfo for the elements inside a HashMap containing Strings and Objects

I'm struggling with deserializing a JSON file that I do not control. The structure of the file is as follows: { "some-identifier": { "@class": "some-prefix.ClassA", "<classA-property1>": "value1", "<classA-property2>": "valu ...

Filtering JSON array data in Typescript can help streamline and optimize data

Recently diving into Angular, I am facing a challenge with filtering data from a JSON array. My goal is to display names of items whose id is less than 100. The code snippet below, however, is not producing the desired result. list : any; getOptionList(){ ...

Parsing JSON instances using either an array or a string data type

When attempting to parse JSON data using Jackson, the instance can sometimes be found as an array or a string. JSON DATA instance with String : { "Value" : "1" } JSON DATA instance with Array : { "Value" : ["ram","kumar"] } This situation leads to ...

Determine the present height of the current class and substitute it with another class that has the same

My wordpress blog theme has an ajax pagination feature that works well, except for the fact that when a user clicks on the next page link, the entire posts area disappears while the new content is loading. I would like to maintain the same container dimens ...