Javascript JSON for each with array of feeds

json array
json.parse array of objects
get value from json object in javascript
how to get data from json array in php
json array of arrays
json nested arrays
json multidimensional array
javascript parse json array

In my example I am trying to fetch the ID and Description from each feed listed in my array feedUrls, but the order of how each feed is fetched doesn't match.

As shown below the result is not from first to last feed in my array, although they the feeds are listed in the array feedUrls from 001 to 005.

var feedUrls = ["https://api.myjson.com/bins/nkvdl", "https://api.myjson.com/bins/13wd2h", "https://api.myjson.com/bins/1b1kbt", "https://api.myjson.com/bins/10zc7d", "https://api.myjson.com/bins/60sqx"];

var arrayData1 = [];
var arrayData2 = [];

var getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
      callback(null, xhr.response);
    } else {
      callback(status, xhr.response);
    }
  };
  xhr.send();
};

feedUrls.forEach(function(entry) {
getJSON(entry,
  function(err, data) {
    if (err !== null) {
      alert('Something went wrong: ' + err);
    } else {
      try {
        arrayData1.push("<li>" + data[0].id + "</li>");
      } catch (e) {}
      document.getElementById('listId1').innerHTML = arrayData1.join("");
    }
  });
});

feedUrls.forEach(function(entry) {
getJSON(entry,
  function(err, data) {
    if (err !== null) {
      alert('Something went wrong: ' + err);
    } else {
      try {
        arrayData2.push("<li>" + data[0].title + "</li>");
      } catch (e) {}
			document.getElementById('listId2').innerHTML = arrayData2.join("");
    }
  });
});
ul {
display: inline-block;
}
<ul id="listId1">empty</ul>
<ul id="listId2">empty</ul>

forEach() provides an index to the callback, which you can use in order to collect the results in their expected order, something like

var feedUrls = ["https://api.myjson.com/bins/nkvdl", "https://api.myjson.com/bins/13wd2h", "https://api.myjson.com/bins/1b1kbt", "https://api.myjson.com/bins/10zc7d", "https://api.myjson.com/bins/60sqx"];

var arrayData1 = [];
var arrayData2 = [];

var getJSON = function(url, callback, index) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
      callback(null, xhr.response, index);
    } else {
      callback(status, xhr.response, index);
    }
  };
  xhr.send();
};

feedUrls.forEach(function(entry, index) {
getJSON(entry,
  function(err, data, index) {
    if (err !== null) {
      alert('Something went wrong: ' + err);
    } else {
      try {
        arrayData1[index]="<li>" + data[0].id + "</li>";
      } catch (e) {}
      document.getElementById('listId1').innerHTML = arrayData1.join("");
    }
  },index);
});

feedUrls.forEach(function(entry, index) {
getJSON(entry,
  function(err, data) {
    if (err !== null) {
      alert('Something went wrong: ' + err);
    } else {
      try {
        arrayData2[index]="<li>" + data[0].title + "</li>";
      } catch (e) {}
			document.getElementById('listId2').innerHTML = arrayData2.join("");
    }
  },index);
});
ul {
display: inline-block;
}
<ul id="listId1">empty</ul>
<ul id="listId2">empty</ul>

JSON Arrays, In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined. Arrays in JSON Objects. Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined. Arrays in JSON Objects

You are using asynchronized request. Asynchronized request will respond in random order. You may never know when it will arrive. And this is expected behavior in ajax. But if you insist that response order REALLY matters, here's the solution for you:

<ul id="listId1">empty</ul>
<ul id="listId2">empty</ul>
<script>
  var feedUrls = ["https://api.myjson.com/bins/nkvdl", "https://api.myjson.com/bins/13wd2h", "https://api.myjson.com/bins/1b1kbt", "https://api.myjson.com/bins/10zc7d", "https://api.myjson.com/bins/60sqx"];

var arrayData1 = [];
var arrayData2 = [];

var getJSON = function(url, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open('GET', url, false);
  xhr.send(null);
  var status = xhr.status;
    if (status === 200) {
      callback(null, xhr.response);
    } else {
      callback(status, xhr.response);
    }

};

feedUrls.forEach(function(entry) {
getJSON(entry,
  function(err, data) {
    if (err !== null) {
      alert('Something went wrong: ' + err);
    } else {
      try {
        var data = JSON.parse(data);
        arrayData1.push("<li>" + data[0].id + "</li>");
      } catch (e) {}
      document.getElementById('listId1').innerHTML = arrayData1.join("");
    }
  });
});

feedUrls.forEach(function(entry) {
getJSON(entry,
  function(err, data) {
    if (err !== null) {
      alert('Something went wrong: ' + err);
    } else {
      var data = JSON.parse(data);
      try {
        arrayData2.push("<li>" + data[0].title + "</li>");
      } catch (e) {}
      document.getElementById('listId2').innerHTML = arrayData2.join("");
    }
  });
});
</script>
<style>
ul {
display: inline-block;
}
</style>

Notice that the xhr request is opened with the third parameter false. This implies that xhr object is sync. (Although it's deprecated.) And sync xhr cannot set response type. So I had to parse the response in callback functions. Hope it helps!

JSON: What It Is, How It Works, & How to Use It, An introduction to JSON (JavaScript Object Notation) and how it's used, of any developer's toolkit: the ability to load and manipulate JSON feeds from other sites Each photo entry is stored in an array called items , which we access in our  You need to loop through the array and then parse the stringified JSON so that you can access the data array. Then simply loop that data array to get the value of each name property.

Here is an updated version using Promise to make the API calls once then sort and display the data.

We do this because

  1. We should only call the API again if we need new or updated data, not because we only grabbed one property and we need two
  2. Promise instead of callback because it allows us to chain these together and "wait for all"
  3. For a specific order, we need to make all the API calls and then we can sort the data (as one collection of data vs. two individual arrays)

const feedUrls = ["https://api.myjson.com/bins/nkvdl", "https://api.myjson.com/bins/13wd2h", "https://api.myjson.com/bins/1b1kbt", "https://api.myjson.com/bins/10zc7d", "https://api.myjson.com/bins/60sqx"];

const arrayData = [];

const getJSON = (url, callback) => {
  // use a Promise to be able to use .then
  // and Promise.all so that we can process
  // all of the API calls before subsequent code
  const promise = new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = () => {
      const status = xhr.status;
      if (status === 200) {
        resolve(xhr.response);
      } else {
        reject(xhr.response);
      }
    };
    xhr.send();
  });
  return promise;
};

// promises is an array of Promise objects
// from the multiple getJSON calls
const promises = feedUrls.map((entry) => {
  return getJSON(entry)
    .then((data) => {
      arrayData.push(data[0]);
    })
    .catch((err) => {
      alert('Something went wrong: ' + err);
    });
});

// Promise.all's .then will only be done once all
// of the API calls are complete
Promise.all(promises).then(() => {
  // sort the data by id
  const sorted = arrayData.sort((a, b) => a.id - b.id);
  // build the li elements from the sorted data
  document.getElementById('listId1').innerHTML = sorted.map((x) => `<li>${x.id}</li>`).join("");
  document.getElementById('listId2').innerHTML = sorted.map((x) => `<li>${x.title}</li>`).join("");
});
ul {
  display: inline-block;
}
<ul id="listId1">empty</ul>
<ul id="listId2">empty</ul>

How to Use JSON Data with PHP or JavaScript – Tania Rascia, Although JSON resembles an object or an array, JSON is a string. the JSON feed echo $characters[0]->name; foreach ($characters as  JavaScript for loops iterate over each item in an array. JavaScript arrays are zero based, which means the first item is referenced with an index of 0. Referencing items in arrays is done with a numeric index, starting at zero and ending with the array length minus 1.

jQuery.getJSON(), which is typically a JavaScript object or array as defined by the JSON structure and For example, all strings represented in JSON, whether they are properties or "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";. $. convert json array to javascript array. 3. For-each over an array in JavaScript. Question feed To subscribe to this RSS feed, copy and paste this URL into

Working with JSON, JSON is a text-based data format following JavaScript object syntax, which Next, we use a for loop to loop through each object in the array. JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be a valid JSON object. Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.

Get JSON Feeds (getJson method) – Cordial Knowledge Base, A {foreach} statement is the most common way to loop through the data array and render the results in a message. Arrays of objects are absolutely iterable. Arrays dont care whats inside them, they just iterate. I didn’t know they were parsing a response with the property containing a JSON array.

Comments
  • You are doing an async request to each URL. The responses can come in any order - either do a request, wait, do the next or do all requests and order the responses.
  • Thanks VLAZ! Do you know of any good solution for me? The biggest problem for me would be that I wouldn't know the number of feeds I would have in the first array, and I need to match the id and title side by side, to know from which id the title belongs to etc. So to order the reponses wouldn't work for me, but your first suggestion with a wait sounds interesting.
  • This is still making the API calls twice, which is unneeded.
  • @crashmstr Yes, you are right. I have not really looked into what happens, just made the order-thing, and nothing else. This way the change is minimal, which may or may not be important.
  • Thank you, using the indexing works well for me, selected as answer.