Access numerical values from JSON objects using JavaScript

I need assistance with implementing a JavaScript function to retrieve data from a JSON file and then display it on my webpage. The goal is to iterate through the values in a while loop and dynamically insert them into specific HTML elements.

  
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var vt = JSON.parse(this.responseText);
	
	while () { // Loop through each value and insert into HTML
	  document.getElementsByClassName("box-href")[i].href = vt.sux27.link;
	  document.getElementsByClassName("box-img")[i].src = vt.sux27.img;
	  document.getElementsByClassName("box-cat")[i].innerHTML = vt.sux27.categories[1];
	  document.getElementsByClassName("box-head")[i].innerHTML = vt.sux27.title;
	  document.getElementsByClassName("box-desc")[i].innerHTML = vt.sux27.description;
	  document.getElementsByClassName("box-likes")[i].innerHTML = vt.sux27.rating;
	  document.getElementsByClassName("box-author")[i].innerHTML = vt.sux27.author_name;
	  document.getElementsByClassName("box-author")[i].href = vt.sux27.author_link;
	  i++;
	}
  }
};
xhttp.open("GET", "https://www.global.cf/website-frontend/articles/articles.json", true);
xhttp.send();

This is the JSON data I am working with:

{
  "sux27": {
    "img":"https://placecorgi.com/320/240",
    "categories" : ["#nature", "#pets"],
    "title" : "Best corgis to get",
    "description" : "This article contains a cute corgi These dogs are extremely hardy, and will kill without hesistation...",
    "link" : "https://www.global.cf",
    "rating" : 27,
    "author_name" : "Pex co",
    "author_link" : "www.pex.com"
  },
  "cat": {
    "img":"http://placekitten.com/320/240",
    "categories" : ["#pets", "#gross"],
    "title" : "Cats up the wazzou",
    "description" : "Do you love dirty yet found cute by some, yet spread desease? Get a cat! This is totaly for u",
    "link" : "pets.com/pets",
    "rating" : 0,
    "author_name" : "Pets.com",
    "author_link" : "pets.com"
  }
}

Answer №1

When you have to iterate through an object, one approach is to use the Object.keys method to transform it into an array. This will allow you to then employ various array iteration techniques.

Object.keys(vt).forEach( (item, id) => {
   // Within this block, 'item' represents each key in the object
   document.getElementsByClassName("box-href")[id].href = vt[item].link
   // Repeat this process for the remaining elements as needed
})

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

How can I manually transclude content within a directive into two separate locations?

When trying to access the result of ng-repeat, I discovered that using the transclude function and manually compiling could help. However, this method does not work in situations with two places and elements containing ng-repeat. Here is how my code is str ...

Completely Erase a Row from JSON

Does anyone know how to completely remove a specific line from a JSON when using a deletion method? I have a button that determines which line should be removed, but even though the correct index is passed in, the row does not get deleted entirely and just ...

Create a regular expression that matches a combination of alphabets and spaces, but does not allow for

Can anyone provide a regular expression that allows for a combination of alphabets and spaces, but not only spaces? After searching extensively and reading numerous articles, I came across the expression /^[a-zA-Z\s]*$/, which unfortunately permits j ...

Convert an R data frame into a simple JSON format

I'm looking to convert a basic data frame in R into a plain JSON object and add multiple variables to a data.js file. Here's the data frame I want to work with: df <- data.frame(Person=c("Dan", "Tom", "Max"), Apples=c(3,5,8), Pears=c(1,0,2), ...

At what point should you invoke db.close() while utilizing cursor.forEach()?

When working with .toArray(), it is common practice to include db.close() within the callback function. For example: db.collection('grades').find(query).toArray(function(err, docs) { if (err) throw err; console.dir(docs); db.close(); }); ...

JavaScript communication between clients and servers

I am looking to develop two scripts, one for the client-side and one for the server-side. I came across a snippet that allows for asynchronous calling of JavaScript: <html> <head> </head> <body> <script> (function() { ...

Tips for updating Vuex getter value during Vue testing?

I'm working on a simple test scenario where I have the following code: describe('App', () => { let store; beforeEach(() => { store = new Vuex.Store({ modules: { auth: { n ...

Shuffle array elements in JavaScript

I need help with manipulating an array containing nested arrays. Here's an example: const arr = [[red,green],[house,roof,wall]] Is there a method to combine the nested arrays so that the output is formatted like this? red house, red roof, red wall, g ...

Error 56 EROFS encountered when trying to save a file in Node.js filesystem every 2 seconds

I've set up a node.js environment on my raspbian system and I'm attempting to save/update a file every 2/3 seconds using the code below: var saveFileSaving = false; function loop() { mainLoop = setTimeout(function() { // update data ...

Extracting Hidden Links: Retrieve the URL that is exclusively visible on the webpage, but not in the source code

While browsing a website, I came across a link that I want to access. However, the link is displayed on the website but is not visible in the HTML file. There is a copy button that allows the link to be copied to the clipboard. I am wondering if anyone k ...

The Vue.js error message "Unable to access property 'array_name' as it is undefined" indicates an issue with

I'm currently working on fetching data using Axios requests and storing it in an array. Below is the code I have been using: props: [ 'products', ], data: function () { return { algolia: '', pro ...

Struggling to make a JavaScript program that sums up odd numbers

Let's tackle this challenge: Your task is to create a program that adds up all the odd numbers between 1 and the number provided by the user. For instance, if the user inputs 7, the program should calculate 1 + 3 + 5 + 7. The result of this calculati ...

Tips for clearing an array, resetting values in a for loop, and creating a Json string simultaneously

Working with an Excel sheet in Python using the openpyxl import, I am iterating through each row to create a Json string for an API input. However, I am facing an issue where splitting a cell value and adding it as a nested array creates unexpected results ...

Ways to retrieve JSON string from responsetext in JavaScript

After spending the entire day on this, I still can't figure it out. I have AJAX that fetches a JSON string from a PHP script, but now I need to work with it in JavaScript. Here's what I've tried: var xmlhttp; xmlhttp=new XMLHttpRequest(); ...

What is the best way to clear an arrayList when an error occurs in the ajax response?

Within my code, I have initialized an empty arrayList as var selection11Data = [];. Data is retrieved from an AJAX call as shown below: var selectionId=trData.selectionId; console.log("here"); $.ajax({ url : A_PAGE_ ...

Commitment failing to deliver the information

I am currently attempting to retrieve data based on a specific ObjectId using promises. The function is successfully fetching the data from the database, but it is failing to return the result as expected. Below is the code snippet: getScreenDetails = fun ...

The alert message fails to appear during an Ajax request

I'm having trouble understanding why the Ajax function in this code snippet is not triggering the success or error functions: function get_cust_key(custid) { $.ajax({ type: "POST", url: 'http://localhost/Test/index.php/getCust ...

Creating a serial number in a Class without relying on a global variable is a useful technique that

I am looking for a way to assign a unique ID to each instance of a Class without relying on global variables. I have tried using a global variable and incrementing it, but I would prefer a more efficient approach. Is there a way to generate an ID within t ...

Tips for generating various series using dx-Chartjs

Trying to visualize ratings based on their type is proving to be difficult as I can't seem to figure out how to group the series according to types. The available chart options are: $scope.chartOptions = { dataSource: data, c ...

After selecting a delivery method, the checkout feature on opencart 1.5.6.4 is malfunctioning

Check out my online shop at store.suhaskhamkar.in. I've set it up using OpenCart version 1.5.6.4, but I'm facing an issue with the checkout process. It seems to get stuck at step #4, which is the Delivery method selection. Upon checking the conso ...