0

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

James
  • 47
  • 1
  • 5
  • Declare `var cars, people` outside the functions. You should also go through basics about variables and scopes in JS – Anurag Srivastava Apr 04 '20 at 20:36
  • I got this error msg. json.html:56 Uncaught TypeError: people is not iterable at json.html:56 (anonymous) @ json.html:56 VM921:1 Uncaught SyntaxError: Unexpected token i in JSON at position 2 at JSON.parse () at json.html:33 at XMLHttpRequest.rawFile.onreadystatechange (json.html:24) (anonymous) @ json.html:33 rawFile.onreadystatechange @ json.html:24 XMLHttpRequest.send (async) readPeopleJSON @ json.html:27 – James Apr 04 '20 at 20:40

0 Answers0