This is the JSON format of the API I am using:
{
"details":[
{
"id": "001",
"name": "john",
"age": "19"
},
{
"id": "002",
"name": "Adam",
"age": "18"
},
{
"id": "003",
"name": "Smith",
"age": "19"
}
],
"students":[
{
"id": "001",
"status": "Active"
},
{
"id": "003",
"status": "Active"
}
]
}
What my goal is to compare the id from the details array with the id from the students array and print any matches found.
My Code:
var data, len, len1, id, name, age, status;
const api_url = "API URL";
async function get_data_from_api() {
const response = await fetch(api_url);
data = await response.json();
len = Object.keys(data["details"]).length;
len1 = Object.keys(data["students"]).length;
for(let i=0; i< len; i++){
for(let j=0; j<len1; j++){
if(data['details'][i]['id'] == data['students'][j]['id']) {
id = data['details'][j]['id'];
name = data['details'][i]['name'];
age = data['details'][i]['age'];
status = data['details'][j]['status'];
document.getElementById('details').innerHTML += "<tr><td>"+id+"</td><td>"+name+"</td><td>"+age+"</td><td>"+status+"</td></tr>";
}
}
}
}
setInterval(get_data_from_api, 1000);
get_data_from_api();
This for loop in my code keeps printing the results repeatedly until the length of the array is reached.
Expected Output:
001 John 19 Active
003 Smith 19 Active
Current Output:
001 John 19 Active
003 Smith 19 Active
001 John 19 Active
003 Smith 19 Active
001 John 19 Active
003 Smith 19 Active