Tips for effectively directing JSON response to populate a table

I recently started learning ajax and I'm looking for some guidance. I'm currently working on fetching data through an API, and while I am able to see the response in the console, I'm struggling with targeting the specific data that I need to populate a table.

Can anyone help me understand how I can target the scores within the JSON response so that I can display them under each category in the table? The scores are dynamic and vary based on the category.

Form:

<form class="pagespeed">
  <input type="text" id="url" placeholder="Enter webpage URL" />
  <input type="button" value="Analyse Webpage" onclick="loadAnalysis()" />

  <div id="analysisTable"></div>
</form>

AJAX function:

JSON response example:

Sample:

Answer №1

lighthouse.categories.length will result in 0 since it is referencing an object rather than an array. To iterate over the keys, you should use Object.keys.

Take a look at the example provided below where we utilize Object.keys to loop through each category entry and extract the row count using length.

Last but not least, we focus on the property:

jsonResponse["lighthouseResult"][categories[r]];
and then add the score attribute.

//var data = this.responseText; //original
var data = '{"lighthouseResult":{"categories":{"performance":{"score":1.0},"accessibility":{"score":0.9},"best-practices":{"score":0.92},"seo":{"score":0.7},"pwa":{"score":0.54}}}}'

var jsonResponse = JSON.parse(data);
console.log(jsonResponse["lighthouseResult"]);
var table = document.createElement('table');
table.setAttribute('class', 'result');
var properties = ['performance', 'accessibility', 'best-practices', 'seo', 'pwa'];
var capitalize = function(s) {
  return s.charAt(0).toUpperCase() + s.slice(1);
}
var tr = document.createElement('tr');
for (var i = 0; i < properties.length; i++) {
  var th = document.createElement('th');
  th.appendChild(document.createTextNode(capitalize(properties[i])));
  tr.appendChild(th);
}
table.appendChild(tr);
var tr, row;
console.log("jsonResponse", jsonResponse);

var categories = Object.keys(jsonResponse["lighthouseResult"]);
for (var r = 0; r < categories.length; r++) {
  tr = document.createElement('tr');
  row = jsonResponse["lighthouseResult"][categories[r]];
  for (var i = 0; i < properties.length; i++) {
    var td = document.createElement('td');
    td.appendChild(document.createTextNode(row[properties[i]].score));
    tr.appendChild(td);
  }
  table.appendChild(tr);
}
document.getElementById('analysisTable').appendChild(table);
<div id="analysisTable"></div>

By utilizing Object.keys, there exists potential for enhancing the code structure. Observe this refined version:

//ES6 example
//var data = this.responseText; //original
const data = '{"lighthouseResult":{"categories":{"performance":{"score":1.0},"accessibility":{"score":0.9},"best-practices":{"score":0.92},"seo":{"score":0.7},"pwa":{"score":0.54}}}}'

const jsonResponse = JSON.parse(data);

const table = document.createElement('table');
table.setAttribute('class', 'result');

const capitalize = function(s) {
  return s.charAt(0).toUpperCase() + s.slice(1);
}

const trHeader = document.createElement('tr');
//save the category names to an array using Object.keys
const categories = jsonResponse["lighthouseResult"].categories;
const categoriesKeys = Object.keys(jsonResponse["lighthouseResult"].categories);

//use arrays forEach functions
const trBody = document.createElement("tr");

categoriesKeys.forEach( function(item) {

  const th = document.createElement('th');
  th.appendChild(document.createTextNode(capitalize(item)));
  trHeader.appendChild(th);
  
  const td = document.createElement('td');

  td.appendChild(document.createTextNode(categories[item].score));
  trBody.appendChild(td);  
  
});

table.appendChild(trHeader);
table.appendChild(trBody);

document.getElementById('analysisTable').appendChild(table);
<div id="analysisTable"></div>

Answer №2

Don't overlook the score property that is present in each section of your data.

td.appendChild(document.createTextNode(row[properties[i]]));

Instead, it should be:

td.appendChild(document.createTextNode(row[properties[i]].score));

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 modifying the border of an entire column in react-table

My goal is to adjust the style according to the screenshot below. This is what I expect: However, this is what I currently have: As you can see, the border bottom of the last column is not applied as expected. I have tried using the props provided by r ...

The behavior of Android webview varies when executing JavaScript code

I am currently involved in a project that involves reading user input via voice and displaying it on a website. I am able to read all input IDs on the site using Jsoup. WebView webView = (WebView) findViewById(R.id.webview); webView.getSetting ...

What is the reason for Nightwatch running each .js file as a Child process? Could it be due to alterations in the configuration settings

Recently, I've been experiencing an issue when running Nightwatch.js where my console is spawning child processes for every .js file in each folder and subfolder. Multiple Chrome instances are opening along with them and even the module folders with r ...

Bind the ajaxStart() and ajaxStop() events exclusively to the current backbone view

For the app I'm currently developing, I am utilizing backbone. Within this application, there is a master view that renders a template containing two other views - a header view and a content view. The header view serves the purpose of interacting wit ...

Retrieve octet-stream information from azure eventhub utilizing node.js

I am new to working with Microsoft Event Hub and I have successfully managed to read sample string data from the EventHub using a Node.js consumer. However, I now need to consume octet-stream data. Here is my code: var messageHandler = function (myIdx, ms ...

Learn to Generate a Mathematical Quiz with Javascript

For a school project, I am tasked with developing a Math Quiz which showcases questions one at a time. The questions vary in type, including Multiple Choice, Narrative Response, Image Selection, Fill in the blank, and more. I require assistance in creatin ...

It is necessary for ReactJS eslint rules to employ destructuring when assigning state

class MyDrawer extends Component { const modalOpen = this.state; // Initialize state in the constructor render() { return ( <div> <Drawer modal open={this.state.modalOpen} // <-- this line show error ...

JSON data for DataTables

I encountered a task that requires me to populate data in datatables from a JSON object. To achieve this, I implemented the following code: $('#example').dataTable( { "data": dataSet, "columns": [ { "title": "Engine" , "data" : "fieldName1"}, ...

Having trouble getting the mock module to work with mockImplementation

I have been facing a challenge in properly testing this File. Some tests require mocking the entire module, while others only need specific methods mocked. I have tried various combinations, but currently, for one specific test below, I am attempting the f ...

"An error has occurred stating that the header is not defined in

It is a coding issue related to payment methods. The headers type is undefined in this scenario, and as a newcomer to typescript, pinpointing the exact error has been challenging. An error message is indicating an issue with the headers in the if conditio ...

Deploying an Angular application created using Yeoman to Heroku

I have been following some instructions on how to deploy my project, such as this guide or this tutorial. However, I am unable to get it to work properly. This is the code in my server.js file: var app, express, gzippo, morgan; gzippo = require('gz ...

$_POST is unable to read POST parameters when using AJAX

I've been facing an issue with sending data to my PHP script. Interestingly, everything works smoothly when using POSTMAN and the results are displayed correctly. However, when attempting to send the data through AJAX in my HTML project, the PHP scrip ...

What are the benefits of using .factory instead of declaring a variable in AngularJS?

As I delve into learning Javascript and Angular JS, I'm exploring alternative approaches to using .factory. Instead of declaring what it returns as a variable and referencing it, I'm curious if there's a way around using factory. Why is fac ...

Can an older version of C++ be utilized with a C++ library?

Recently, I've been exploring the idea of using JSON as the file format for my latest C++ project. Unfortunately, I haven't had much luck finding a library that specifically supports C++17. While there are options like nlohmann/json and RapidJSON ...

Is there a way to prevent users from downloading PDFs or docs when they are opened in a new tab in a React application?

I recently encountered a situation where I needed PDF files to open in a new tab, but restrict the download for certain users. Despite trying out various third-party packages in React, none of them successfully rendered the PDF files as required. If poss ...

Get rid of the seconds in the output of the toLocaleTimeString

The method Date.prototype.toLocaleTimeString() provides a language-sensitive representation of the time part of a date in modern browsers. Unfortunately, this native function does not offer an option to exclude the display of seconds. By default, it shows ...

A collection of items that mysteriously affix themselves to the top of the page as

Unique Context In my webpage, I have a specific div element with the CSS property of overflow: auto. Within this scrolling div, there is structured content like this: <h3>Group A</h3> <ul> <li>Item 1</li> <li>I ...

The database is storing inaccurate values after being sent through a POST request in a REST API

I am encountering a strange issue when attempting to save JSON data into my Postgres database using the POST command in a RESTful API. The data is being accepted, but for some reason, the key-value pairs are getting swapped with each other. I have provided ...

Unable to unmarshal the object in JSON-RPC

Currently, I am delving into understanding how JSON-RPC operates and decided to test it out in Go language (golang). The Go program seems to be functioning perfectly fine as intended. However, when attempting to make a raw request via telnet, an error aris ...

Form validation displaying only the initial error message

When validating a form, I am encountering an issue where only the first error message can be displayed: ContactUs.prototype.desktopErrors = function(){ var THIS = this; THIS.$el.find('#submit').on('click', function(){ ...