Node.js: Using a for loop to iterate through a JSON array and extract all unique identifiers

I am encountering an issue with extracting the different ids from my json object. The only id I seem to be able to retrieve is that of the last item.

Below is the function in question:

var xmlhttp = new XMLHttpRequest();
var url = "https://wjko5u2865.execute-api.us-east-2.amazonaws.com/articles"; 
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
   var allart = JSON.parse(this.responseText);
    for(let i = 0; i < allart.Items.length; i++)
    {
      document.getElementById("id").innerHTML = allart.Items[i].id;
    }
  }
};
xmlhttp.open("GET", url, true);
xmlhttp.send();

This is the json array that I am receiving:

{
  "Items":[{
    "marca":"Guzzi",
    "titolo":"Moto Guzzi V100 Mandello, la regina di EICMA 2021",
    "id":"123456",
    "immagine":"moto_guzzi_v100_mandello.jpg",
    "data":"27/11/2021"
    },
    {
    "marca":"Bimota","titolo":"Bimota: arriverà un'adventure su base Tesi",
    "id":"135623",
    "immagine":"bimota-_arrivera_unadventure_su_base_tesi.jpg",
    "data":"04/12/2021"
    },
    {
    "marca":"Ducati",
    "titolo":"Ducati, la DesertX sarà svelata a Dubai il 9 dicembre",
    "id":"123789",
    "immagine":"b_desertx-dwp2022-2-uc336332-high.jpg",
    "data":"04/12/2021"
    },
    {"marca":"Benelli",
    "titolo":"EICMA 2021, Benelli \"sforna\" le moto più attese",
    "id":"146975",
    "immagine":"benelli_2.jpg",
    "data":"27/11/2021"
    }
    ],
    "Count":4,"ScannedCount":4}
  

Thank you in advance for your help

Answer №1

The mistake in your code lies with this particular line:

document.getElementById("id").innerHTML = allart.Items[i].id;

To rectify it, you need to include a "+" before the "=" sign to concatenate additional strings/ids to the innerHTML.

document.getElementById("id").innerHTML += "<br/>"+allart.Items[i].id;

I devised an alternative approach wherein I utilized Array.prototype.map() to generate an array consisting of all the ids and then employed Array.prototype.join() to amalgamate them into a single string.

var xmlhttp = new XMLHttpRequest();
var url = "data:application/json;base64,ewogICJJdGVtcyI6W3sKICAgICJtYXJjYSI6Ikd1enppIiwKICAgICJ0aXRvbG8iOiJNb3RvIEd1enppIFYxMDAgTWFuZGVsbG8sIGxhIHJlZ2luYSBkaSBFSUNNQSAyMDIxIiwKICAgICJpZCI6IjEyMzQ1NiIsCiAgICAiaW1tYWdpbmUiOiJtb3RvX2d1enppX3YxMDBfbWFuZGVsbG8uanBnIiwKICAgICJkYXRhIjoiMjcvMTEvMjAyMSIKICAgIH0sCiAgICB7CiAgICAibWFyY2EiOiJCaW1vdGEiLCJ0aXRvbG8iOiJCaW1vdGE6IGFycml2ZXLgIHVuJ2FkdmVudHVyZSBzdSBiYXNlIFRlc2kiLAogICAgImlkIjoiMTM1NjIzIiwKICAgICJpbW1hZ2luZSI6ImJpbW90YS1fYXJyaXZlcmFfdW5hdmVkbnR1cmVfc3VfYmFhdHQicCIKICAgICJkYXRhIjoiMzk2LzExLzMwMjEtMTQ6NDUifSwKICAgIHsi...
xmlhttp.send();
<div id="id"></div>

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

Obtain a string value from a JavaScript object

My dilemma involves a specific Javascript object. { A: 1, B: 2, C: 2, D: 1, E: 1, F: 4, G: 6, H: 2 }, The goal is to extract a four-letter string based on the key with the highest value, but there are limitations. The stri ...

Limiting the display of JSON data on a webpage using jQuery

I have a code snippet on my website that displays JSON data on an HTML page. The issue is that there is a large amount of data in the JSON file. How can I limit the number of movies (data) being displayed to just 5? function actors(actors) { return ` ...

Discovering a specific string amidst two other strings across multiple lines in php

Having the source code of an old website with significant javascript arrays to retrieve, the task seems daunting for manual extraction. The data now needs to be integrated into a database, prompting the idea of creating a parser in PHP to gather the data i ...

Exploring the method of retrieving nested JSON objects in Angular

When my API sends back a JSON response, my Angular application is able to capture it using an Interface. The structure of the JSON response appears as follows: { "release_date":"2012-03-14", "genre_relation": ...

When using $.getJSON, the callback function fails to execute

The Issue: The callback function in my $.getJSON request is not executing. When the page loads, nothing is displayed in the console or on the page. However, when the function is manually entered into the console, it works as expected. Here is the jQuery ...

Identify when a browser tab is closed and determine which specific tab out of all the open tabs was closed

Is there a way to identify when a browser or tab is closed in Angular/JavaScript? I would like to know if there are specific events that can be used for detecting these actions. Any advice, information, or code examples on this topic would be greatly app ...

Is there a way to manipulate text in JQuery without altering the inner element?

I am struggling with an issue in my HTML code. Currently, I have the following structure: <h3 id="price">0.00<sup id="category">N/A</sup></h3> My intention is to use AJAX to replace the content within the <h3 ...

JavaScript event handler for dynamic button click

I am creating a unique button dynamically for each row in a table to handle deletions. I am assigning the id of the button with the key of the row, allowing me to retrieve it later when clicked. Since all buttons share the same function, passing the specif ...

Utilize key value pairs to retrieve data from a multi-level array

I'm looking for assistance with extracting values from an array based on key value rather than array number. $json = json_decode($stock, true); print_r($json); $sims = $json['stock'][1]['sims']; foreach ($sims as $sim) { echo ...

trouble with maintaining nodejs mariadb connection

Hello, I am working with nodejs to create a rest API However, I have encountered an issue Let's take a look at the code var http = require('http'); var url = require('url'); var mariadb = require('mariadb'); http.c ...

Guide to uploading a file into a MongoDB database with the help of Mongoose

Currently, I am working on a database application using Node-Express and mongoose. My goal is to enable users to upload various file types such as photos or documents directly into the database. Despite searching extensively for information online, I hav ...

What is the best way to extract parameters from a JSON object?

Here is the complete code: $.post('test.php', { id: id },function (data) { console.log(data); var Server = data.response.server; var Photo = data.response.photo; console.log(Server); console.log(Photo); }); When I receive data I get JSON data ...

I am looking to utilize jQuery to dynamically update a selected checkbox through AJAX

I've been struggling to make my ajax json script update my HTML checked box with the value from the database, but so far I haven't had any luck. Any assistance would be greatly appreciated! Here's the JS code snippet: setInterval(functi ...

Which is better for creating hover effects: CSS3 or JavaScript?

When hovering over a link, I want to highlight a specific picture and blur the rest. Here's my HTML code: <body> <div id="back"> <div id="one"></div> <div id="two"></div> </div> ...

The loading bar animation doesn't begin at a blank slate

I'm currently working on a project that utilizes Django for the backend and Bootstrap for the frontend. I have to admit, I am quite inexperienced when it comes to front-end development; JavaScript seems like magic to me. One of the key features I nee ...

AngularJS - Establishing communication between controller and view

I am facing an issue with the Angularjs view. I seem to be making a mistake somewhere and I can't figure out where the problem lies. I hope someone can assist me with this. The problem is that {{user.login}} (userRepoInfo.html file) is not being call ...

Using asp.net along with Ajax for dynamic web development

I need to update my JavaScript code in order to refresh a different page window.opener.location.replace(url) However, a problem arises when trying to specify the path to the root where the page is located. Currently, the calling code is placed in a page ...

Can the state and city be filled in automatically when the zip code is entered?

I have a form where users can enter their zip code, and based on that input, the corresponding city and state will automatically populate. These three fields are positioned next to each other within the same form. Here is an example of my form: $(' ...

A step-by-step guide to invoking a function upon submitting a form with an external JavaScript file

How can I execute a function when the user submits a form using an external JavaScript file? index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>example</title> ...

Executing a function without a callback within an Async library

I am facing an issue with this particular example mentioned in the Async documentation: async.map(['file1','file2','file3'], fs.stat, function(err, results) { // results is now an array of stats for each file }); In this ...