How do I access "people" from readPeopleJSON function and "cars" from readCarsJSON function in the for loop at end of my code? Please help me. Thank you in advance.
People.json:
[{id: 1, name: "Tom", carid: 1},{id: 2, name: "Bob", carid: 1},{id: 3, name: "Sir Benjamin Rogan-Josh IV", carid: 2}];
cars.json
[{id: 1, name: "Ford Fiesta", color: "blue"},{id: 2, name: "Ferrari", color: "red"},{id: 3, name: "Rover 25", color: "Sunset Melting Yellow with hints of yellow"}];
//Get Peple from people.json
function readPeopleJSON(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readPeopleJSON("people.json", function(text){
var people = JSON.parse(text);
});
//Get Cars from cars.json
function readCarsJSON(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("application/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readCarsJSON("cars.json", function(text){
var cars = JSON.parse(text);
});
//List People and car deatils
const result = [];
for (const peop of people) {
const car = cars.filter(d => d.id === peop.carid)[0];
result.push({
person_name: peop.name,
name: car.name,
color: car.color
});
}
console.log(result);
This is the result i'm looking for.
Name: Tom
Car Name: Ford Fiesta
Color: blue