Traverse the array of nested JSON objects in an iterative manner

I need to iterate through a JSON array object with the following structure:

var myJSONObject = {
    "abc": {
        "prod_1": [
            {"prod_ver" : "prod 1 ver 1"},
            {"prod_ver" : "prod 1 ver 2"},
        ],
        "prod_2": [
            {"prod_ver" : "prod 2 ver 1"},
            {"prod_ver" : "prod 2 ver 2"},
        ],
        "prod_3": [
            {"prod_ver" : "prod 3 ver 1"},
            {"prod_ver" : "prod 3 ver 2"},
        ]
    }
};

The task involves looping through the product names and their respective versions. Each product name contains a list of its versions.

I am looking for a JavaScript solution that can handle multiple products and versions dynamically, providing the product name and version separately in variables for further processing.

If there is a better JSON structure or any suggestions for improvement, please advise on the appropriate format.

Your assistance is much appreciated.

Answer №1

In order to improve the structure of your JSON data, it would be beneficial to define the property abc as an array since it contains a list of products. You can do this by redefining it like so:

var myJSONObject = 
{
"abc":
    [
        [
            {"prod_ver" : "prod 1 ver 1"},
            {"prod_ver" : "prod 1 ver 2"},
        ],
        [
            {"prod_ver" : "prod 2 ver 1"},
            {"prod_ver" : "prod 2 ver 2"},
        ],
        [
            {"prod_ver" : "prod 3 ver 1"},
            {"prod_ver" : "prod 3 ver 2"},
        ]
    ]
};

By structuring your data in this way, you can easily iterate over the products and their versions using standard loops:

for(var i = 0; i < myJSONObject.abc.length; i++)
{
    var product = myJSONObject.abc[i];
    for(var j = 0; j < product.length; j++)
    {
        var version = product[j];
    }
}

If you want to enhance the readability of your JSON object further, you could consider adjusting its structure slightly:

var catalog = 
{
    "products": [
        {
            "name": "prod 1",
            "versions": [
                "ver 1",
                "ver 2"
            ]
        },
        {
            "name": "prod 2",
            "versions": [
                "ver 1",
                "ver 2"
            ]
        }
    ]
};

for(var i = 0; i < catalog.products.length; i++)
{
    var product = catalog.products[i];
    var productName = product.name;
    for(var j = 0; j < product.versions.length; j++)
    {
        var version = product.versions[j];
    }
}

Answer №2

myJSONObject.abc is an object containing keys such as prod_1, prod_2, and so on. By using a for-in loop, you can iterate through the keys of an object like this:

var productName;
var productVersionArray;

for (productName in myJSONObject.abc) {
    productVersionArray = myJSONObject.abc[productName];
}

It's important to note that the order of the keys may vary depending on the JavaScript engine being used. To control the order, you can obtain an array of keys, sort them, and then loop through the sorted array. In environments supporting ES5, you can get an array of keys using Object.keys(yourObject). For older browsers, a shim would be required.

Within the loop, you can further iterate through the array using a standard for loop:

for (versionIndex = 0; versionIndex < productVersionArray.length; ++versionIndex) {
    // Access `productVersionArray[versionIndex].prod_ver` here
}

The following example demonstrates putting these concepts into practice:

(function() {

  var myJSONObject = 
    {
    "abc":
        {
            "prod_1": 
            [
                {"prod_ver" : "prod 1 ver 1"},
                {"prod_ver" : "prod 1 ver 2"}
            ],

            "prod_2": 
            [
                {"prod_ver" : "prod 2 ver 1"},
                {"prod_ver" : "prod 2 ver 2"}
            ],
            "prod_3": 
            [
                {"prod_ver" : "prod 3 ver 1"},
                {"prod_ver" : "prod 3 ver 2"}
            ]
        }
    };

  var productName;
  var productVersionArray;
  var versionIndex;

  for (productName in myJSONObject.abc) {
      productVersionArray = myJSONObject.abc[productName];
      display(productName + " has " + productVersionArray.length + " versions listed");
      for (versionIndex = 0; versionIndex < productVersionArray.length; ++versionIndex) {
        display("* " + productVersionArray[versionIndex].prod_ver);
      }
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = String(msg);
    document.body.appendChild(p);
  }

})();

Live Example | Source Code

Answer №3

Enhanced using ES6 syntax

  let { items } =
    {
        "items": [
            {
                "title": "item 1",
                "options": [
                    "opt 1",
                    "opt 2"
                ]
            },
            {
                "title": "item 2",
                "options": [
                    "opt 1",
                    "opt 2"
                ]
            },
            {
                "title": "item 3",
                "options": [
                    "opt 1",
                    "opt 2"
                ]
            }
        ]
    };

    const stockList = items.reduce((previous, current) => {
        let { title, options } = current;
        previous[title] = options
        return previous
    }, []);

    Object.entries(stockList).forEach((item) => {
        let itemName = item[0];
        let itemOptions = item[1].join(", ");
    });

Answer №4

function outputProperties() {
  for (let property in myJSONObject.xyz) {
    let propValue = myJSONObject.xyz[property];
    for (let j = 0; j <= propValue.length; j++) {
      console.log(propValue[[j]]);
    }
  }
}

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

Error message in my Angular project: Invalid Target Error

Out of nowhere, I encountered an invalid target error while running my Angular project with the command: npm start An unhandled exception occurred: Invalid target: {"project":"agmbs","target":"build","configur ...

How can I eliminate the hover effect from a div element?

I am facing an issue with implementing a zoom effect on hover for my list of products. When I do a long press on a product, it works the first time but not the second time. I suspect this is because the div remains in a hover state. I want to ensure that ...

How can we combine multiple arrays into a single JSON object using json_encode in PHP?

I am new to PHP and am attempting to merge 2 arrays into a single JSON object. Currently, the JSON output looks like this: { "image_link": "some url", "zoomin_level": "8", "zoomout_level": "18.5", "position_lat": "32.913105", "positio ...

Angular 9: Chart.js: Monochromatic doughnut chart with various shades of a single color

My goal is to display a monochromatic doughnut chart, with each segment shaded in varying tones of the same color. I have all the necessary graph data and just need to implement the color shading. ...

Breaking down nested date lists within DataFrame columns to calculate the average hour

Assuming we have the following DataFrame: ID date_time 1 2020-03-13 21:10:56, 2020-06-02 22:18:06, 2020-04-14 22:10:56, 2021-06-02 22:18:06 2 2010-09-13 21:43:09, 2011-05-04 23:08:15,2012-06-04 23:08:16 3 2013-06-14 23:29:17, 2014-08-13 23:20:2 ...

Issue encountered while parsing JSON data in FastAPI: JSON.parse error - unexpected end of data at line 1 column 1

Greetings, I have a python fast api backend server set up. @app.get("/getName") async def getName() -> JSONResponse: data_sniffer = DataSniffer() data = json.dumps(data_sniffer.get_data()) print(data) return JSONResponse(content=data,heade ...

When Ajax sends an HTTP Get request to an MVC Controller with a complex JSON object as a parameter, the controller receives it as null

I am currently working with three classes: public class MainSearch { public MainSearch() { SearchData searchData = new SearchData(); SearchMode searchMode = new SearchMode(); } public SearchData searchData { get; set; } ...

Activate onbeforeunload when the form is not submitted

Currently, I have a form that is submitted using PHP with three different submit actions: Save and Continue Save and Exit Exit without Saving The goal is to trigger an "OnBeforeUnload" alert if the user does not click on any of the form actions. This al ...

Leveraging Watchers on props in Vue 3's Script Setup

When passing a prop to a component that declares its state, I am attempting to watch the prop and set the CSS styling accordingly. However, for some reason it is not working as expected. Can anyone help me figure out what might be wrong? <script setup ...

What steps should be taken to retrieve the contents of a file that has been chosen using the browse

You have successfully implemented a browse button that allows the user to navigate the directory and choose a file. The path and file name are then displayed in the text element of the Browse button complex. Now, the question arises - how can I extract dat ...

Fill a grid child with an excessive amount of content without specifying a fixed height

Check out this JS Fiddle example .grid { height:100%; display:grid; grid-template-rows:auto 1fr; background-color:yellow; } .lots-of-content-div { height:100%; background-color:orange; overflow-y:auto; } <div class="grid"> <p&g ...

Switching to '@mui/material' results in the components failing to render

I have a JavaScript file (react) that is structured like this: import { Grid, TextField, makeStyles } from '@material-ui/core' import React from 'react' import {useState} from 'react' //remove this function and refresh. see ...

Basic AngularJS application, however I am receiving {{this is supposed to be the information}}

Building an angularjs app I have set up an asp.net mvc4 application and integrated the angularjs package using nuget. The Layout.cshtml file has been updated to look like this: <!DOCTYPE html> <html ng-app="myApp"> <head> <meta ...

The Slider component in Material UI's API may not properly render when using decimal numbers as steps or marks in React

I am having trouble creating a Material UI slider in my React application. I can't figure out which property is missing. Below is the code for my React component: import * as React from 'react'; import Slider from '@material-ui/core/S ...

Setting up Npm Sequelize Package Installation

Could use some help with setting up Sequelize. Here's the current status: https://i.sstatic.net/MQH1I.jpg ...

Having issues transferring the variable from JavaScript to PHP?

When attempting to pass a variable via AJAX request in JavaScript, I am encountering an issue where the variable is not being received in my PHP file. I'm unsure of where the problem lies. Can anyone help? JavaScript code var build = { m_count : ...

What is the best way to hide the jQuery modal I created?

Hello everyone! Currently, I am working on coding a simple JS modal that can be opened and closed smoothly. The issue I am facing is related to adding a click function to (.black-overlay) in order to fade out everything and close the modal. <div class ...

Implement a button transformation upon successful completion of a MySQLi update using AJAX

When displaying multiple database results with buttons that can be turned on or off inside a div, I am looking to implement AJAX to toggle the button state between ON and OFF upon clicking, and then update the button without refreshing or reloading the ent ...

Next JS is successfully importing external scripts, however, it is failing to run them as

In my upcoming project using the latest version 12.1.6, I am incorporating bootstrap for enhanced design elements. The bootstrap CSS and JS files have been included from a CDN in the pages/_app.js file as shown below: import '../styles/globals.css&apo ...

Ways to expand a Bootstrap input field by clicking on it:

I have successfully created a search bar in my navbar, but I am looking to add functionality that allows the input field to expand to its normal size when clicked. I believe this will require some JavaScript implementation, however, I am unsure how to proc ...