What is the best way to display this JavaScript data structure?

I'm having some trouble with a for loop as I attempt to display the details array within my data structure.

for(i in myObj.detail){
  x += "<h2>" + myObj.detail[i].bigtitle + "</h2>";  

  for(z=0; z<3; z++){   
     x+="<h2>"+ myObj.detail[i].infor[i].step[z] + "</h2>"; 
     for(m=0; m<3; m++){

       x+="<h2>"+ myObj.detail[i].infor[i].image[m] + "</h2>"; 

         for(c=0; c<3; c++){

            x+="<h2>"+ myObj.detail[i].infor[i].content[c] + "</h2>"; 
           }
        }
     }
 }  



myObj={"detail":[{
         "bigtitle":"Print Room",
         "lable":3,        
         "infor":[{"step":["First","Second","Third"]},
                  {"image":["imge-1","imge-2","image-3"]},
                  {"content":["1111","2222","3333"]}
                 ]}
               }

the result should look like this:

Print Room 

  First
  imge-1
  1111
  Second
  imge-2
  2222
  Third
  image-3
  3333

Answer №1

Using multiple unnecessary loops in your code can lead to errors and exceptions. Instead, simplify your code by using just two loops:

  • The first loop should iterate over myObj.detail by using myObj.detail.length to access all elements in the array.
  • The second loop should iterate over the step, image, and content entries with a fixed counter of 3.

Your revised code should look like this:

var x = "";
for (i in myObj.detail) {
  x += "<h2>" + myObj.detail[i].bigtitle + "</h2>";
    for (m = 0; m < 3; m++) {
      x += "<h2>" + myObj.detail[i].infor[0].step[m] + "</h2>";
      x += "<h2>" + myObj.detail[i].infor[1].image[m] + "</h2>";
      x += "<h2>" + myObj.detail[i].infor[2].content[m] + "</h2>";
    }
}

Check out the demo below:

myObj = {
  detail: [{
    bigtitle: "Print Room",
    lable: 3,
    infor: [{
        step: ["First", "Second", "Third"]
      },
      {
        image: ["imge-1", "imge-2", "image-3"]
      },
      {
        content: ["1111", "2222", "3333"]
      }
    ]
  }]
}

var x = "";
for (i in myObj.detail) {
  x += "<h2>" + myObj.detail[i].bigtitle + "</h2>";
    for (m = 0; m < 3; m++) {
      x += "<h2>" + myObj.detail[i].infor[0].step[m] + "</h2>";
      x += "<h2>" + myObj.detail[i].infor[1].image[m] + "</h2>";
      x += "<h2>" + myObj.detail[i].infor[2].content[m] + "</h2>";
    }
}

document.write(x);

Answer №2

It's worth trying to access this JSON data without using a loop, as it is straightforward and can help manage CPU usage efficiently. Here's an example:


console.log(myObj.detail[0].bigtitle);
console.log(myObj.detail[0].lable);
console.log(myObj.detail[0].infor[0].step[0]);
console.log(myObj.detail[0].infor[0].step[1]);
console.log(myObj.detail[0].infor[0].step[2]);
console.log(myObj.detail[0].infor[1].image[0]);
console.log(myObj.detail[0].infor[1].image[1]);
console.log(myObj.detail[0].infor[1].image[2]);
console.log(myObj.detail[0].infor[2].content[0]);
console.log(myObj.detail[0].infor[2].content[1]);
console.log(myObj.detail[0].infor[2].content[2]);

Link to view code on CodePen

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

Utilize JavaScript to zero in on the search term when searching

Apologies if it's difficult to grasp. I need to write some code that focuses on the specific word we want to search for. Here's an example: Imagine this scenario: when we land on the page, the checkboxes are populated from a database table nam ...

Tips on making a bubble similar to the one on the Google homepage that prompts you to make Google your default homepage

I am looking for a subtle way to suggest visitors to make my website their homepage. While I considered using a popup, I didn't want it to be too intrusive for the visitor to see a large popup every time they visited the website. I'm interested ...

What is the best way to eliminate an object from an array of objects that fulfills a specific condition?

Upon receiving an object in my function containing the information below: { "name": "Grand modèle", "description": "Par 10", "price": 0, "functional_id": "grand_modele_par_10", "quantity": 2, "amount": 0 } I must scan the next array of objec ...

Combining Components in NextJs Without Using Functional Components

I created a module, then split it into components and now I'm trying to piece it back together. The individual components are functioning correctly. Some components are nested inside the div of another component. I attempted to group them within a d ...

Storing data in variables from a single div using Javascript

Within a div element, there lies a number that undergoes constant changes. An example of this is: <div id="current">124</div> A JavaScript function has been implemented to retrieve the data from this specific field and store it in a JavaScrip ...

Creating tube-like geometry in intervals using three.js

Is there a way in Tube Geometry(Three.js) to plot and render only a portion of the tube at a time, with the option to continue plotting from that point after a set interval or timer? ...

Guide to swapping images based on conditions using Angular JS

I am trying to display an image based on data received from an API response instead of text. If the value is true, I want to show an access symbol. If the value is false, I want to show a deny symbol. However, when attempting this, I am only getting th ...

How can the order of elements in an array be reset after deletion using PHP?

I need help with managing an array. Here is an example of the array before and after deleting an element: array(3) { [0]=> array(3) { ["id_coach"]=> int(1) ["nom_coach"]=> string(4) "kaka" } [1]=> array(3) { ...

The list of items in a React Bootstrap Dropdown does not refresh when the state is changed

Trying to implement a dropdown with a list of checkboxes using react-bootstrap. The toggle event on the checkboxes works, but I'm facing an issue where the component is not re-rendered and the checkbox does not reflect the change. Check out the code ...

Transferring the jQuery modal variable value to a PHP script

I feel like I might be making this more complex than it needs to be, but I'm working on a jQuery modal that communicates with a PHP file. The PHP file contains the form and validation logic, and the modal includes this file. The modal is triggered by ...

What causes RangeError: Maximum call stack size exceeded when Element UI event handlers are triggered?

I'm currently working on setting up a form and validating it with Element UI. Despite closely following the documentation, I am encountering an issue where clicking or typing into the input boxes triggers a RangeError: Maximum call stack size exceeded ...

Trouble encountered while attempting to choose a single checkbox from within a v-for loop in Vue.js?

<div id="example-1"> <ul> <input type="text" v-model="searchString" placeholder="Filter" /> <p>sortKey = {{sortKey}}</p> <li v-for="item in sortedItems"> <input class="checkbox-align" type="checkbo ...

Keeping an eye on the location and retrieving articles once more - Vuejs

ClassController <?php namespace App\Http\Controllers\Classes; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\ClassCategory; use App\Models\Article; use App& ...

"Troubleshooting a jittery React sticky header during scrolling: Dealing with IntersectionObserver and CSS

My current project involves implementing a sticky header in a React application using the Carbon framework. The goal is to have a sticky header with a bottom border when users scroll up, providing context for their viewing experience. However, when they sc ...

Is there a way to determine if scroll events are triggered just once, similar to how they are on touch devices?

When it comes to iOS devices (and possibly Android ones), the scrolling behavior is quite different. The scroll event is triggered only once after the entire scroll process has been completed. Is there a way for me to determine if the browser follows this ...

What is the reason for being able to initialize an array within a struct using the array name

This is the code to initialize array elements in a struct I am initializing man1 using the member-order format I am initializing man2 using the .member_name format However, I am confused by .array_name = "string" I know int array[4] = ...

Display and conceal button while scrolling in both directions

Seeking assistance with solving a coding challenge. I have created a function that reveals a button (an arrow pointing from bottom to top) when scrolling down. Now, I aim to implement another feature where the button appears after scrolling over 500 pixe ...

Uploading files asynchronously in Internet Explorer 8

Currently, I am on the lookout for sample code that allows asynchronous file uploads in IE8 using Ajax. While having upload progress would be a bonus, it is not essential. Moreover, I specifically need PHP code to handle the uploaded files on the server ...

Struggling to extract data from a text input in my API capstone project

Greetings everyone, this is my first post here on this platform. (please excuse the current CSS design, it's a project in development) Here is the link to my repl-it: https://repl.it/@Johnmexico/BlandElegantOrigin-1 Let me provide a brief overview. ...

PHP retrieve rows with matching first words - must be exact matches

$companies = array( array('id' => '1','name' => 'Fifo Limited'), array('id' => '2','name' => 'FIFO Ltd'), array('id' => '3','name& ...