While delving into the world of JavaScript and JSON with limited programming knowledge, I am attempting to showcase all the names within the friends array in a single line separated by commas. Here is the data file I am working with that I found on the internet:
Here is the snippet of my array: [ { "age": 25, "eyeColor": "blue", "name": "Leon Pickett", "phone": "+1 (834) 535-2787", "balance": "$3,632.41", "address": "856 Woodhull Street, Southmont, Wisconsin, 373", "friends": [ {"id": 0,"name": "Bonnie Dudley"}, {"id": 1,"name": "Blair Hopkins"}, {"id": 2,"name": "Burris Lara"} ] }, { "age": 29, "eyeColor": "brown", "name": "Rosales Raymond", "balance": "$3,632.41", "phone": "+1 (935) 462-3887", "address": "745 Havens Place, Norvelt, Florida, 6999", "friends": [ {"id": 0,"name": "Theresa Burt"}, {"id": 1,"name": "Mooney Whitney"}, {"id": 2,"name": "Hebert Gill"} ] } ]
Displayed below is the code snippet I currently have:
var xmlhttp = new XMLHttpRequest();
var txt = "jsontst1.txt";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", txt, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var out2 = "";
var i, j;
for (i = 0; i < arr.length; i++) {
var frndlngth = arr[i].friends.length;
for (j = 0; j < frndlngth; j++) {
var frnds = arr[i].friends[j];
out2 += frnds.name;
}
out +=
"Name = " + arr[i].name + "<br>" +
"Age = " + arr[i].age + "<br>" +
"Phone = " + arr[i].phone + "<br>" +
"Balance = " + arr[i].balance + "<br>" +
"Eyecolor = " + arr[i].eyeColor + "<br>" +
"Address = " + arr[i].address + "<br>" +
"Friends = " + out2 + "<hr>";
}
document.getElementById("id01").innerHTML = out;
}
Why does the output display values from the previous array as well? What mistake am I making here?