Navigating through nested JSON arrays in JavaScript involves looping through multiple dimensions

I am facing difficulty finding the correct solution to my issue here. I am trying to iterate through the nested Products arrays in order to display each Product name. Can this be achieved with my current code, or should I consider rewriting it to make querying easier for me?

            [
               {
                  "category":"A",
                  "products":[
                   {
                     "id":1,
                     "name":"Product 1",
                     "description":"Description of product 1."
                   },
                   {
                     "id":2,
                     "name":"Product 2",
                     "description":"Description of product 2."
                   },
                   {
                     "id":3,
                     "name":"Product 3",
                     "description":"Description of product 3."
                   }
                  ]
               },
               {
                  "category":"B",
                  "products":[
                   {
                     "id":4,
                     "name":"Product 4",
                     "description":"Description of product 4 in category B."
                   },
                   {
                     "id":5,
                     "name":"Product 5",
                     "description":"Description of product 5 in category B."
                   },
                   {
                     "id":6,
                     "name":"Product 6",
                     "description":"Description of product 6 in category B."
                   }
                  ]
               }
            ]

Answer №1

If we assume that the entire configuration is stored in a variable named data:

data.forEach(function(category) {
    if (category.hasOwnProperty('product')) {
        category.products.forEach(function(product) {
            console.log(product.name);
        });
    }
});

The outer loop using forEach iterates over all the category objects, while the inner loop goes through each product object within every category.

Answer №2

When it comes to iterating through arrays, the conventional method is as follows:

for( var i=0; i<array.length; i++ ) {
    // perform actions on array[i]
}

For objects, the process slightly differs:

for( property in object ) {
    if( object.hasOwnProperty(property) ) {
        // perform actions on object[property] or property.
    }
}

Nesting loops is also an option.

In a specific scenario where your data structure is named collection, you can refer to this example (view http://jsfiddle.net/7yc5arLe/):

for( item=0; item<collection.length; item++ ) {
    console.log('category is '+collection[item].category);
    for( product=0; product<collection[item].products.length; product++ ) {
        p = collection[item].products[product];
        for( prop in p ) {
            console.log('  product '+prop+' is '+collection[item].products[product][prop]);
        }
    }
}

The expected output will be:

category is A
  product id is 1
  product name is Product 1
  product description is Description of my product 1.
  product id is 2
  product name is Product 2
  product description is Description of my product 2.
  product id is 3
  product name is Product 3
  product description is Description of my product 3.
category is B
  product id is 4
  product name is Product 4
  product description is Description of my product 4 in cat B.
  product id is 5
  product name is Product 5
  product description is Description of my product 5 in cat B.
  product id is 6
  product name is Product 6
  product description is Description of my product 6 in cat B.

Answer №3

Absolutely, it can be done.

  • For traversing through an array [] :

    for (starting point; condition; increment) {
        ...
    }
    
  • For iterating over an object {} :

    for (item in object) {
        if (object.hasOwnProperty(item)) {
            ...
        }
    }
    

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

The data retrieved using Ionic 3 Angular Fire's payload.val() seems to be returning

Is it possible to determine whether a profile is filled in or empty when using Firebase Database for storing profile information? Currently, I am utilizing profile.payload.val(), but it seems to return null in both cases instead of true when the profile is ...

Jquery-ajax fails to accomplish its task

I am just starting to learn about ajax and recently created a simple page on my local server to practice sending and receiving data from/to a JSON file in the same directory. Although the GET method is working perfectly fine, I am having trouble understan ...

The lua.vm.js ajax callbacks are triggering, but unfortunately, the requested data is not

After raising this issue at https://github.com/kripken/lua.vm.js/issues/5, I realized that submitting it to stackoverflow might yield a faster response due to higher exposure. To ensure clarity, I will restate my question: How can the callback data be acce ...

Looking to automate the selection of a dropdown menu using Selenium with JavaScript

Below is the code snippet for a drop-down: <div class="w-1/2 px-8 pt-6"> <div class="Styled__FieldWrapper-sc-1fqfnqk-1 bQZNMa mb-6"> <label class="form-label" for="transfer.account">Transfer Acc ...

Retrieving Values from Array with AngularJS Keys - A How-To Guide

I need to access a specific value from a key inside an array, like this: $scope.result = [ { "key":"logo_big", "value":"/assets/images/aaa.jpg" }, { "key":"logo_small", "value":"/assets/images/logo94x57Bis.png" }, { ...

Accessing HP ALM with REST and JavaScript on a local server: A step-by-step guide

I am trying to access ALM using locally written JavaScript in the browser (IE11, Firefox) through the REST API, but I am unable to login. Below is the code snippet where I am attempting to request the LWSSO cookie with jQuery: var auth = btoa(USER+":"+PAS ...

How can I adjust the time in a range slider using AngularJS?

Currently, I am utilizing a Slider with draggable range in angular js for time selection. The Slider can be found here: https://jsfiddle.net/ValentinH/954eve2L/. I aim to configure the time on this slider to span from 00.00 to 24.00, with a 10-minute inter ...

Passing data to an Angular directive

I am facing an issue while trying to pass information through a view in a directive. Despite binding the scope, I keep seeing the string value 'site._id' instead of the actual value. Below is the code for the directive: angular.module('app ...

What steps can I take to avoid keypress events causing issues with the browser's input functionality?

Utilizing Bootstrap's modal component, I have implemented an "Add User" dialog within my web application. In order to streamline the user experience and enable quick data entry, I am aiming for the escape and enter keys to close and submit the form re ...

Parsing JSON without a default constructor defined

As I transition an existing communication layer to utilize REST with JSON, I encounter a challenge with the default constructor of the transferring POJOs not being required by the previous framework. Unfortunately, making changes to the model classes bein ...

Rotate images using a JQuery plugin without using HTML tags, solely through passing the images in JavaScript

I am currently working on creating a jQuery image rotator from scratch. While I know there are simple jQuery sliders/rotators available, I specifically want to include the image files directly within the JS code. I do not want to use this HTML structure: ...

Options menu in an Android Studio application

Having just begun my journey with Android Studio, I am facing difficulties in creating a menubar. Despite my efforts to find solutions, none of them seem to work out. I attempted the following code snippet, but I feel stuck at this point: public class Ma ...

Creating a subform using a Mongo query from a JSON entry

I am looking to extract specific information from the document. Specifically, I want access to only the Variables listed in the entry below, formatted as follows. Document1:{ "META" : { "CATEGORY" : "Boxes", "CREATEDBY" : " ...

It is imperative that the query data is not undefined. Be certain to provide a value within your query function that is not undefined

I am utilizing a useQuery hook to send a request to a graphql endpoint in my react.js and next.js project. The purpose of this request is to display a list of projects on my website. Upon inspecting the network tab in the Chrome browser, the request appear ...

What is the reason behind the `inputs` function skipping the initial line of the input file?

Would you like to know why I only receive back all lines except the first when using jq with the `inputs` command and providing a file? My current version of jq is 1.6, and my goal is to convert a TSV (Tab Separated Values) into JSON by setting the first ...

Issue with CSS transition not displaying ng-show elements properly

I'm currently working on incorporating a fade-in effect for text using the second solution from this source when using ng-show. Here is my HTML setup: <input ng-focus="hasFocus = true" ng-blur="hasFocus = false" type="text" placeholder="Cli ...

Comparison between PHP's JSON parser and Javascript's JSON parser

Can anyone help me with this PHP serialize JSON encoding issue? json_encode(array('pattern' => '^(?:/?site/(?[\w\-]+))?(?:/?intl/(?[a-z]{2}(?:\-[a-z]{2})?)/?)?(/?(?.*))')); // output json: {"pattern":"^(?:\/?site ...

Embracing the beauty of incorporating nested quotations

I've been experimenting with jquery's append functions lately. I'm adding a substantial amount of html, specifically a button with an onclick event function. It might sound complicated, but due to some technical restrictions, this is my onl ...

Enhancing user experience with dynamic element integration in jQuery's AutoComplete feature

In order to fulfill my requirement, I need to display a few options when the user enters at least three characters in one of the input fields, which may be added dynamically as well. Since the data is extensive, I am unable to load it at the beginning of ...

How can I identify and return false if all the digits from 0 to 9 are matching with other characters in a string?

In my current project, I am focusing on filtering out numerical values only. I have implemented a phone mask using JavaScript on the front end to filter user input to a specific format such as (000)000-000, which includes numbers ranging from [2-9] and [0- ...