Exploring nested arrays in JSON through iteration

Here is the JavaScript code I am working on (the "data" variable is retrieved from a json call):

if (data.projectReports.length) {
  for (var i in data.projectReports){
    var report = data.projectReports[i];
    $('#reports').append(
        '<div class="report-description">' +
          '<h2>' + report.header + '</h2>' +
          '<p>' + report.text + '</p>' +
        '</div>' +
        '<ul class=\"report-moreinfo\">' +

          // Loop through the "persons" object here.

        '</ul>'
    );
  }
} else

. . .

This is my JSON data:

{
  "projectReports":[
    {
      "header":"Headline",
      "text":"Description of item",
      "estimate":10,
      "actual":7,
      "persons":{
        "Robert":5,
        "Erik":10,
        "Juan":3
      }
    }
  ]
}

I'm still learning about JSON and encountered some challenges when attempting to loop through the "persons" object within each report. After researching various solutions, I decided to seek assistance by providing all necessary details here.

My goal is to iterate over report.persons where the comment is placed in my JavaScript code.

Prior solutions were straightforward when referencing specific keys like "header" or "text", but this time I only have key-value pairs. How can I achieve this?

<li><p> persons.key </p><p> persons.value </p></li>

I recognize that I will need another nested for loop, but I lack the expertise to construct it on my own.

Answer №1

This is some basic information

var peopleData = "";
for (var x in persons){
   if (persons.hasOwnProperty(x)){
     console.log(x);          // the key
     console.log(persons[x]); // the value
     // concatenate it all together
     peopleData += "<li><p>"+x+"</p><p>"+persons[x]+"</p></li>";
   }
}

and then:

$('#reports').append(
    /* ... */
    '<ul class=\"report-moreinfo\">' +
    peopleData +
    '</ul>';
    /* ... */
);

Answer №2

To optimize your code, it would be ideal to implement a function that iterates through reports.persons and retrieves the necessary information:

var showPersons = function(persons){
  var appendedData = '';
  for (var person in persons) {
    if (!persons.hasOwnProperty(person)) continue;
    appendedData += '<li><p>' + person + '</p><p>' + persons[person] +'</p></li>'
  }
  return appendedData;
};

You can then utilize this function to add all the relevant data within the <ul> tags:

listPersons(report.persons);

If you prefer a structure where you can reference person.name and person.value, your JSON should follow this format:

{
    "projectReports": [
        {
            "header": "Headline",
            "text": "Description of item",
            "estimate": 10,
            "actual": 7,
            "persons": [
                {
                    "name": "Robert",
                    "value": 5
                },
                {
                    "name": "Erik",
                    "value": 10
                },
                {
                    "name": "Juan",
                    "value": 3
                }
            ]
        }
    ]
}

Answer №3

Utilize the for (.. in ..) loop

$('#reports').append(
    '<div class="report-description">' +
      '<h2>' + report.header + '</h2>' +
      '<p>' + report.text + '</p>' +
    '</div>' +
    '<ul class=\"report-moreinfo\">');

for (var personKey in report.persons){
  $('#reports').append('<li><p>' + personKey + '</p><p>' + report.persons[personKey] + '</p></li>');
}

$('#reports').append(
    '</ul>'
);

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

Tips for looping through multiple states within a single table

I need help with combining data from two different states, campaigns and stats, into a single table. The campaigns state includes sr no, campaign id, campaign name, and campaign status, while the stats state includes reach, sent, delivered, views, clicks ...

extracting data from a JSON file containing numerous JSON objects

I encountered an issue with my JSON file that was generated as a response from running multiple parallel curl statements (GET requests to a service). When attempting to parse the JSON file using Python, I faced an error due to multiple JSON objects being ...

incorporate a new component in real-time

I need help with dynamically adding components to my container in AngularJS. I have a componentA that functions as a container, and I want to add multiple instances of componentB when a button is pressed. Currently, I can successfully add a single instanc ...

Why is it that when I return a JSONResult from an overridden JSON method it doesn't function, but a ContentResult does

Recently I encountered an unusual situation while attempting to override the Json method of a Controller class in order to utilize JSON.net contract resolver. Strangely, everything works as expected when I return an object of ContentResult and cast it to A ...

While attempting to import modules in Visual Studio Code, an error message appears stating "Unexpected token {"

Greetings! I am currently using Visual Code to run my project and would like to share my code with you. In the file external.js: export let keyValue=1000; In the file script.js: import {keyValue} from './external.js'; console.log(keyValue); ...

The onChange function in React JS for a Material UI 'number' TextField retains the previous value

In this element, I have an onChange function: <TextField id="rowinput" type="number" defaultValue={this.defaultRows} // defaultRows = 1 inputProps={{ min: "1", max:"5"}} onChange= ...

Display toggle malfunctioning when switching tabs

I am currently working on implementing a search function with tabbed features. Everything seems to be displaying correctly without any errors. However, the issue arises when I try to click on any tab in order to show or hide specific content from other tab ...

Modify the fixed div's class when the user scrolls past a certain section

My page includes a fixed menu with various sections, each assigned a specific class name using data attributes (e.g. data-menu="black"). I want the fixed menu to change its class based on the section that is currently underneath it as the user scrolls. Y ...

What is the best way to send a file and retrieve a value on Internet Explorer versions 8 and 9?

Greetings everyone, I am encountering a technical issue that has consumed a significant amount of my time. I am hopeful that you may be able to assist me with resolving it. In my table, I have a list of files along with corresponding document types and de ...

Collecting JSON elements into an array on an Android device

My goal is to extract the URLs that come after "unescapedUrl" and store them in a String array. This JSON data includes multiple image search results with corresponding URLs. {"responseData": {"results":[{"GsearchResultClass":"GimageSearch","width":"1916 ...

I'm at a loss with this useState error, can't seem to figure

Could you please help me understand what is incorrect in this code snippet? import React, { useState } from 'react'; import UsrInput from '../component/UsrInput' import TodoItemList from '../component/TodoItemList' const ...

Stop images from flipping while CSS animation is in progress

I've been developing a rock paper scissors game where two images shake to mimic the hand motions of the game when a button is clicked. However, I'm facing an issue where one of the images flips horizontally during the animation and then flips bac ...

The Jest mock for dates is completely ineffective and always ends up returning the constructor

beforeAll(() => { ... const mockedData = '2020-11-26T00:00:00.000Z' jest.spyOn(global, 'Date').mockImplementation(() => mockedData) Date.now = () => 1606348800 }) describe('getIventory', () => { ...

Tips on setting up a dropzone upload feature with a click-trigger option

Is there a way to configure dropzone.js so that the file is uploaded only when a submit button is clicked, rather than automatically? Here's the code snippet I am currently using: $('#myDropzone').dropzone({ url: SITE_URL + 'self_r ...

Learn how to remove data from a React JS application without causing a page refresh by utilizing the useLoaderData() function in conjunction with React Router

I am working on preventing my table from refreshing with the new version of userLoadData from react-router-dom@6 after deleting some data. In an attempt to achieve this, I created a function called products() within useLoaderData. While this function succ ...

Hold off on refreshing the page until all the $.get calls have finished executing

I am currently using a piece of JavaScript to execute an Ajax call which returns XML data. This XML is then processed, and another Ajax call is made for each "record" found in the XML to delete that record. However, I am facing an issue where the JavaScrip ...

Unable to Trigger Virtual Click Event on Calendar in JavaScript

My workplace utilizes a custom web application with a date picker/calendar that I am attempting to modify programmatically. The app is built in Vue, which has added complexity to my task. Despite exhaustive efforts, I have been unable to select or inject d ...

What is the best way to populate a dropdown menu with data and enable users to search for specific items by typing them in?

I need assistance with populating data in a drop-down box that is not pre-defined. The data needs to be dynamically created and then displayed in the drop-down box. Currently, the data is being shown using check boxes, but I want it to appear in a drop-dow ...

Retrieve relevant information from JSON upon scanning the barcode

Dealing with a barcode scanner app specifically designed for warehouse use. Upon scanning an item, the UPC number is successfully displayed. However, I now require the display of additional data associated with that UPC, which needs to be retrieved from a ...

Tips for efficiently serving a static file without triggering a disk read

res.sendFile is the preferred method for serving a static file in express. However, it appears that res.sendFile reads the file from disk with each request, as shown below: router.get('/', (req, res) => { res.sendFile('./guest.js&apo ...