Printing an array within an array from JSON using JavaScript

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?

Answer №1

The reason for the issue is that the out2 variable is global, so its value keeps getting appended instead of resetting after each outer loop.

To solve this problem, make it local within the for-loop.

function myFunction(arr) {
  var out = "";
  var i, j;
  for (i = 0; i < arr.length; i++) {
    var out2 = "";
    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;
}
var input = [{
  "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"
  }]
}];
myFunction(input);
<div id="id01"></div>

Check out the Fiddle Demo here.

Answer №2

If you have an object or array, you can convert it to a string using:

var stringOutput = JSON.stringify(yourObjectOrArray);

You can then display the string with alert(stringOutput).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Does using the "null" parameter in JSON.stringify help prevent circular structures?

Can someone explain the concept of "null" to me? JSON.stringify(myJsonObj, null, 2) I've noticed that some people use "undefined" or "null." I couldn't grasp the purpose of "null," so I decided to remove it. JSON.stringify(myJsonObj) Subsequ ...

The date entered in the input field should also appear in all other textboxes on the

I currently have 2 tables set up on my page. In the first table, there is a textbox (txt1) that includes a date picker. The second table contains 5 similar textboxes (txt2, txt3, txt4, txt5, txt6) also with date pickers. My requirement is as follows: Ini ...

Create a JavaScript array by extracting IDs from an HTML document

Looking to create a function that randomly selects an image defined in HTML code. I've opted to create an array to store all used images and have the function pick from there. Is there a simpler way to define the array or should I skip using it altog ...

Remove rows that have values within a specific range

I'm facing an issue in Google Sheets where I'm attempting to delete entire rows on the "Data" sheet if any value in column B matches values from the range D3:E20 in the "Backend" sheet. The code provided works when a word is hardcoded as the cond ...

Exploring the Depths of React by Cycling Through Arrays in Tabular Format

One issue I'm facing is that I have an array named paymentMethods which I'd like to iterate through in tabs. However, I seem to be struggling with the iteration part. To take a closer look at my code, please visit my codesandbox HERE <div& ...

Can someone please help troubleshoot my ajax code?

My ajax function is calling a php page, but I keep encountering an issue where the error function is being triggered instead of the success function. What could be causing this unexpected behavior? Here is my ajax code: function register() { $.ajax({ ...

Retrieving the data payload from a 400 response using HttpURLConnection

When making a JSON request to my web service, I return a 400 message code with a detailed JSON error response if the request is bad. But how can I retrieve this payload on the client side using HttpURLConnection? The connection's InputStream is null a ...

Unexpectedly, optimization causing issues on Angular site without explanation

Currently, I am utilizing Angular to construct a front-end website that searches for and showcases information obtained through API requests. Whenever I compile the project into a file bundle for static deployment using ng build, I notice that the resultin ...

Deciphering the intricate mechanics behind _.bind

This block of code is an excerpt from the Underscore library, specifically showcasing the implementation of the _.bind function. However, I am struggling to comprehend the purpose behind modifying the prototype of an empty function. var customConstruc ...

Once a unique email address has been created, I aim to reuse it for future correspondence

Issue: During the application process, I encounter a dilemma when prompted to input an email address and confirm it in a separate text field. To automate this task, I rely on webdriverJS for coding. My approach involves generating a random email address u ...

What is the most efficient way to determine the monthly user count using a MongoDB query that takes into account the previous count?

I am looking to calculate the total count of users based on the previous month's count data. Here is an example of how the results array should be structured: RESULTS [ { count: 1, accumulatedCount: 1, month: 12, year: 2021, verified: true }, ...

Troubleshooting issue: Unable to display data using *ngFor in Angular 4

Currently, I am developing an application that utilizes HttpClient to fetch data from a local JSON file. The JSON file contains images and descriptions, with the images also being local. While I am able to successfully log the data in a local array, I am e ...

Unexpected button behavior sparked by Vue.js

Check out this fiddle I created: https://jsfiddle.net/frvuw35k/ <div id="app"> <h2>Vue Event Test</h2> <form @submit.prevent> <div class="form-group row"> <div class="col-sm-12 i ...

Using the power of AJAX, fetch JSON data and render it into display tags

JavaScript Query jQuery.noConflict(); jQuery(document).ready(function(){ jQuery("#stallId").change(function(e){ //prevent default action e.preventDefault(); jQuery.ajax({ url: "getProduc ...

Improving Android's functions using Json data manipulation

I have a JSON file stored on the server: {"images":[ {"url":"...", "likes":"123"}, {"url":"...", "likes":"234"}, {"url":"...", "likes":"345"} ]} After retrieving the JSON file on my Android device, I am wondering if it is possible to update the likes co ...

Inadvertent scroll actions causing unexpected value changes in Material UI sliders

I am currently working on a React application that utilizes Material UI, with slider components integrated throughout the interface. However, I have encountered an issue when using a touch screen device - unintentional changes to the slider values occur wh ...

Passport causing TypeError: req.session.regenerate not recognized as a valid function

Hello! I am currently enrolled in the Node with React full web stack course and I have encountered a major issue. I am unsure of why it is appearing or where it is coming from. The error displayed in my terminal is: req.session.regenerate(function(err) { ...

Obtaining data using PHP and transferring it to a JavaScript variable

Currently, I am in the process of developing an audio player for a project that I am working on. I have this weird idea - is it feasible to retrieve a URL or any data from my MySQL table and then assign it to a JavaScript variable? If it is possible, cou ...

Using AJAX to retrieve additional JavaScript code or functions from the server

It's common knowledge that AJAX is often utilized to request a web part in HTML format from the server. However, is it feasible to use AJAX to request a script that includes functions? ...

The issue with the dispatch function not working in the Component props of React Redux

I'm struggling with my colorcontrol issue. I've been attempting to use this.props.dispatch(triggerFBEvent(fbID, method, params)) without success. Interestingly, it seems to work fine if I just use triggerFBEvent(fbID, method, params). However, I ...