Retrieve information from two linked JSON URLs using JavaScript

Having an issue with JSON in JavaScript regarding 2 different JSON URLs. One URL contains user data and the other contains post data, with a field userId in the posts JSON.

I'm trying to figure out how to connect them effectively. I need to retrieve users and their respective posts, then calculate the number of posts each user has written.

var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
  var posts = JSON.parse(postRequest.responseText);

  var userRequest = new XMLHttpRequest();
  userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
  userRequest.onload = function (){
    var users = JSON.parse(userRequest.responseText);
    for(k in users){
      document.write("</br></br>"+ users[k].name +", " + users[k].username + ", " + users[k].email + "</br>" + "-------------------------------------------------------------------------------------" + "</br>");
      for(k1 in posts){
        if(posts[k1].userId===users[k].id){
          document.write(posts[k1].body + "</br>");
        }
      }
    }
  };
  userRequest.send();

};
postRequest.send();

However, this doesn't seem like an optimal solution. I want to store JSON data in variables for future use, such as within functions. Can anyone offer assistance? I've never connected data from 2 JSON files before and want to learn the best practices.

Answer №1

Try using this code snippet instead:

for(var user in users) {
   for(var post in posts) {
      if(posts[post].userId === users[user].id) {
         if(!users[user].hasOwnProperty('posts')) {
             users[user].posts = [];
         }
         users[user].posts.push(posts[post].body);
      }
   }
}

Answer №2

if you could utilize jQuery

$.when($.ajax({
    url: "https://jsonplaceholder.typicode.com/users"
})).then(function(data, textStatus, jqXHR) {
    $.each(data, function(index, value) {
        $.ajax({
            url: "https://jsonplaceholder.typicode.com/posts?userId=" + value.id
        }).then(function(data, textStatus, jqXHR) {
            console.log("UserID:" + data[0].userId + "   Number of Posts:" + data.length);

        });
    });
});

Feel free to test the code above and inform me if it meets your requirements

Answer №3

Helpful Steps to Follow:

1. Start by including a body property into the objects within the users array based on matching id and userid.

2. Subsequently, you can loop through the users array whenever necessary.

LIVE DEMO

var getRequest = new XMLHttpRequest();
getRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
getRequest.onload = function() {
  var data = JSON.parse(getRequest.responseText);
  var userRequest = new XMLHttpRequest();
  userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
  userRequest.onload = function (){
    var userList = JSON.parse(userRequest.responseText);
    
    for(i in userList) {
      for(j in data) {
        if(data[j].userId===userList[i].id){
          userList[i].body = data[j].body;
        }
      }
    }
    
    console.log("User List", userList);
  };
  userRequest.send();
};
getRequest.send();

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 to ensure a C# web request waits for a webpage to finish loading, including all jQuery and AJAX calls

Hey all! Just had a quick question that I hope someone can help me with. Right now, I'm utilizing an HttpClient to send a request to a website and then parse the data from the page. However, the issue that I'm running into is that a lot of the co ...

ideas for working with json

Which usage is correct? Which one should be used? Below are sample codes that I need a recommendation for. { "__bc" : 1, "_payload" : null, "_plugin" : [.........], "_debug" : "on", "_content" : [ "html":{&l ...

Guide on how to extract data from a local JSON file, retrieve images from the JSON object's URL, and store the image paths in a Model

I currently have the following JSON saved locally: { "country":[ { "alpha2Code":"AF", "alpha3Code":"AFG", "flag":"https://raw.githubusercontent.com/DevTides/c ...

Open a new tab in Chrome and take a screenshot of the freshly created tab

I am encountering an issue with capturing a newly created tab in Chrome. When I use chrome.tabs.create to create a new tab and pass the tabid to my callback function for capturing, it does not work as expected. function createNewTab(url) { chrome.tabs.c ...

What is the reason behind the effectiveness of this prime number verifier?

Take a look at this code snippet that effectively checks whether a number is prime: var num = parseInt(prompt("Enter a number:")); var result = "Prime"; for (var i = 2; i < num; i++) { if (num % i === 0) { result = "Not Prime"; break; } } ...

PHP not cooperating with AJAX POST method, only GET is functioning as intended

I'm having trouble sending a POST request to php using Ajax. When I use GET everything works fine, but with POST the data received in php is empty. I am sending the data as json. Below is the JavaScript code: $.ajax( { type: &ap ...

Tips for customizing the Bootstrap 4 grid system for a seamless mobile viewing experience

My form consists of 3 steps, each row containing multiple inputs. You can see an example of my form here. Below is a sample of the grid system I have used: <div class="row"> <div class="col"> <input asp-for="First_N ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

Exploring Sanity npm package with Jest for mocking tests

I am encountering an issue with mocking some code in my sanity.ts file: import sanityClient from '@sanity/client'; // eslint-disable-next-line @typescript-eslint/no-var-requires const blocksToHtml = require('@sanity/block-content-to-html&ap ...

There was an issue with searching on the YouTube API: com.google.api.client.googleapis.json.GoogleJsonResponseException occurred, showing a 403 Forbidden

I have been diligently following the steps outlined in this tutorial to develop my own Youtube application. I successfully created a Browser-Android API Key and implemented it into my project. However, upon attempting to run the application and conduct a s ...

Struggling to connect the Calendar data in AngularJS

I am a beginner in angular js and facing an issue with binding the value of the calendar date from the jquery calendar picker. It seems to be accepting the date only, while all other fields are getting bound correctly. Below is my HTML code: <input id ...

What is the best way to extract information from a JSON object using Java?

Can anyone assist me in retrieving the value, which is 80000, for the product with the name "Camera" from a JSON format using Java programming?     { "Products":{         "Product":[            {               "Nam ...

Leveraging HeatMap.js, a JavaScript library, within a ReactJS environment

Seeking Assistance I am aiming to implement a heatmapjs running example in ReactJS. How can I achieve this goal? ...

Ways to refresh the child scope in Angular using an array

When receiving an array of data from the server in AngularJS, I need to dynamically update the $scope. The initial value is : $scope.form = {}; I would like to update it dynamically as follows: $scope.form = {"firstname" : "Alex"}; Both 'firstnam ...

Steps for adjusting the port number in a Vue.js CLI project

Is it possible to modify the Port number within a Vue-CLI project in order for it to operate on a different port other than 8080? ...

What is the best method to retrieve data from a SQL table using knex when the row values are in consecutive order?

Imagine I have a database that represents a library, with a table storing the words within each book. Let's refer to this table as "books" and assume it includes rows like the following: | book_name | word_in_book | word | |-----------|----------- ...

Exploring the scope of variables in asynchronous functions

I'm facing an issue while trying to access a variable that was declared inside an async function. Here's the scenario: exports.startTheBasketEngine = async (username, password, domainData) => { const parse = domainData.auctionUrl.split("-" ...

Having trouble with Asp .net ajax autocomplete feature? It seems like the Webmethod is not being triggered as

Could someone explain why the WebMethod is not working on a specific page? The code functions correctly on another page, and even when transferred to a new page. However, when used on the intended page, it fails to trigger the webmethod. I am unsure of wha ...

What is the best method for retrieving the correct city name using latitude and longitude with the Google API?

Using the following query http://maps.googleapis.com/maps/api/geocode/json?latlng=35.6723855,139.75891482, I am able to retrieve a list of various locations based on the provided coordinates. However, I am specifically interested in obtaining only the ci ...

Can images be uploaded via HTTP GET requests?

I've been working on a script for uploading images to a server. I'm curious if there's a way to modify it to use an object instead of form data and switch from POST to GET method. var uploadfileinfo = document.getElementById("upload-fil ...