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.