What is the best way to determine the total number of rows in a JSON file?

Here is the JSON data I have:

[0:{name:"jason",height:"150cm"},
1:{name:"henry",height:"178cm"}]

In my function, I am attempting to create a for loop like this:

        function DrawTable(output) {

            var general = output;
            var sb = new StringBuilder();
            for (var i = 0; i < *total row in the json*; i++)
             sb.append("<td>" + general[0][i]["name"] + "</td>");
             sb.append("<td>" + general[0][i]["height"] + "</td>");
            }

Figuring out how to properly implement this has been a challenge for me.

Answer №1

Let's start off by pointing out that the data provided is not in JSON format.

However, for a hypothetical scenario, let's imagine if it were structured as follows:

[{
    "name": "jason",
    "height": "150cm"
}, {
    "name": "henry",
    "height": "178cm"
}]

In that case, it would be considered valid JSON.

You could then implement a function similar to this:

If you're using jQuery:

function GenerateTable(jsonString) {
    var data = JSON.parse(jsonString);
    var table = createElement('table')
                    .append(
                           createElement('thead')
                              .append(
                                  createElement('tr')
                                      .append(
                                          createElement('th').text('Name'),
                                          createElement('th').text('Height')
                                      )
                              )
                    );
    var body = createElement('tbody');
    data.forEach(function(item) {
                      body
                         .append(
                             createElement('tr')
                                 .append(
                                      createElement('td').text(item.name),
                                      createElement('td').text(item.height)
                                 )
                         );
                  });
    //append body to table and display on the page
}

Alternatively, considering your current code structure:

function GenerateTable(output) {
    var jsonData = JSON.parse(output);
    var stringBuilder = new StringBuilder();
    for (var i = 0; i < jsonData.length; i++) {
        stringBuilder.append("<td>" + jsonData[i].name + "</td>");
        stringBuilder.append("<td>" + jsonData[i].height + "</td>");
    }
}

Answer №2

In the event that your data is structured like this:

{
  0: {name:"jason",height:"150cm"},
  1: {name:"henry",height:"178cm"}
}

instead of being enclosed in an array, you can iterate through Objects.values(yourData) to achieve the desired outcome:

function DisplayInfo(dataObjects) {
  var htmlString = '';
    
  Object.values(objectsData).forEach((object) => {
    htmlString += "<td>" + object.name + "</td>";
    htmlString += "<td>" + object.height + "</td>";
  });
    
  return htmlString;
}

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

Determine whether a variable includes an alphabetic character

I need to eliminate any results from an array that include alphabetic characters. To do this, I am using the following code: if(gtin.toString().length != 13 || /[a-z\-]+/ig.test(gtin) == true) { gtin = "null"; } Although it works for some variab ...

interval-based animation

I'm trying to create a simple animation using setInterval in JavaScript. The goal is to make an image move from left to right. HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"& ...

Is there a way to confirm if one field value is greater than another using the Ajv JSON schema validator?

Is it feasible to receive a validation error using ajv when minPrice exceeds maxPrice? What is the recommended method of achieving this, ideally adhering to the JSON schema standard? ...

PHP code to display "ed elements that do not adjust height"

A php script is being utilized to scan a directory and populate a gallery with all the images. Within the <div id="content"> tag, the function <?php create_gallery("path"); ?> loads all the images. The issue arises when the height of the <d ...

NodeJS: Extract images based on specified coordinates

Dealing with images that contain text can be a challenge, but by using tesseract and the imagemagick node module, I was able to extract the text successfully. The only issue I encountered was related to the image size. https://i.sstatic.net/XldZC.png For ...

Extract a specific pattern from a string using Javascript

Currently, I am attempting to extract a specific string from a tag in javascript using the following code: document.querySelector('.title h2').textContent However, when I execute this code, I am getting a result that includes unnecessary double ...

Tips for managing boolean values in a JSON data structure

My JSON object is causing issues because it has True instead of true and False instead of false. How can I fix this problem? The code snippet below shows that obj2 is not working properly due to boolean values being capitalized. <!DOCTYPE html> < ...

Creating a toggle button for a div element to expand and collapse its content: Step-by-step guide

For my e-commerce site selling musical instruments, I'm designing a product landing page that showcases guitars, keyboards, violins, and cellos. As part of the design, I want to include expandable sections with detailed information about each instrume ...

Updating a global variable in Angular after making an HTTP call

I'm facing a challenge where I have a global variable that needs to be updated after an HTTP GET call. Once updated, I then need to pass this updated variable to another function. I'm struggling to figure out the best approach for achieving this. ...

NodeJs and Mysql query execution experiencing significant delays

NodeJs + Mysql query delays and execution timing issue https://github.com/mysqljs/mysql Hello everyone, I'm facing a problem with mysql js. Whenever I use .query(), the callback is taking too long to execute and returning empty results. However, if I ...

Calculating the hour difference between two time stamps (HH:MM:SS a) using moment.js

I have two time without date var startTime="12:16:59 am"; var endTime="06:12:07 pm"; I need to calculate the total hours between the above times using a library like moment.js. If it's not achievable with moment.js, then please provide a solution u ...

Pass data back and forth between app.js (node) and javascript (main.js)

I am facing a challenge in sending and retrieving data (username) between app.js and main.js. In my setup, I have a node app.js that calls index.html which then triggers the main.js function called "clicked". Below is the code snippets for each file: app. ...

Enable an object to be of specific types within a Swagger definition

Currently, I am working on defining an API and one of the fields is named "payload". Previously, this field was defined as "type": string in our Swagger documentation. However, we have noticed that the payload data now has a structured format. Specifi ...

Tips for clearing all content within a React Material UI table

How can I create a reset button to clear a table filled with user input data, without having to write functions from scratch? For example, similar to using clearLayer() for clearing a leaflet map. Thank you for any suggestions! //example of dynamical ...

Refine keys dynamically according to the given input

I'm facing a challenge with an array wherein I need to filter out keys based on an input string. The only constant key is OLD_VAL, while the others are dynamic. Even though I attempted using a variable, it doesn't retrieve that specific key. let ...

Inconsistencies with AJAX performance

Hey there, I'm a newbie and absolutely loving this site! Currently diving into the world of JavaScript and have been through numerous tutorials. However, I seem to be struggling with getting Ajax to work. Recently stumbled upon this code snippet on ...

vue utilize filtering to search through a nested array of objects within a parent array of objects

After making an API call, I receive JSON-formatted data with a specific structure like this: data = [ { name: 'John', school:[ { school_name: 'Harvard', date_attended: '2017-05-23' }, { schoo ...

Order comments based on their category using vue.js

I have a component form with select filter: <template> <div class="form-group"> <select name="" v-model="filterRev" @change="filterReviews(filterRev)" class="form-control" id=""> <option ...

JavaScript fails to perform without the presence of an alert

Hey there, I've come across a bit of a puzzling situation and I'm struggling to find the right words for the Title of this question. I have a javascript function that is supposed to trigger when the document has finished loading. In the initial p ...

jQuery not refreshing properly

I'm currently in the process of creating a script to switch the language on a website using PHP and Ajax/jQuery. I would like the page content to refresh without having to reload the entire page. So far, this is what I have come up with: $( "a[data-r ...