Foreach for json javascript

How to Loop Through a JSON Response in JavaScript

When fetching data from a remote server, the server’s response will often be in JSON format. In this quick tip, I’ll demonstrate how you can use JavaScript to parse the server’s response, so as to access the data you require.

This process will typically consist of two steps: decoding the data to a native structure (such as an array or an object), then using one of JavaScript’s in-built methods to loop through that data structure. In this article, I’ll cover both steps, using plenty of runnable examples.

What is JSON?

Before we look at how to deal with JSON, let’s take a second to understand what it is (and what it isn’t).

JSON stands for JavaScript Object Notation. It’s a language-independent, text-based format, which is commonly used for transmitting data in web applications. JSON was inspired by the JavaScript Object Literal notation, but there are differences between the two. For example, in JSON keys must be quoted using double quotes, while in object literals this is not the case.

There are two ways data can be stored in JSON:

  • a collection of name/value pairs (aka a JSON object)
  • an ordered list of values (aka a JSON array)

When receiving data from a web server, the data is always a string, which means that it’s your job to convert it into a data structure you can work with.

If you’d like to find out more about how JSON works, please visit the JSON website.

Fetching JSON from a Remote API

In the following examples, we’ll use the fantastic icanhazdadjoke API. As you can read in its documentation, making a GET request where the Accept header is set to application/json will see the API return a JSON payload.

Let’s start with a simple example:

const xhr = new XMLHttpRequest(); xhr.onreadystatechange = () =>  if (xhr.readyState === XMLHttpRequest.DONE)  console.log(typeof xhr.responseText); console.log(xhr.responseText); > >; xhr.open('GET', 'https://icanhazdadjoke.com/', true); xhr.setRequestHeader('Accept', 'application/json'); xhr.send(null); // string // 

As we can see, the server returned us a string. We’ll need to parse this into a JavaScript object before we can loop through its properties. We can do this with JSON.parse():

if (xhr.readyState === XMLHttpRequest.DONE)  const res = JSON.parse(xhr.responseText); console.log(res); >; // Object 

Once we have our response as a JavaScript object, there are a number of methods we can use to loop through it.

Use a for. in Loop

A for…in loop iterates over all enumerable properties of an object:

const res = JSON.parse(xhr.responseText); for (const key in res) if(obj.hasOwnProperty(key)) console.log(`$key> : $res[key]>`) > > // id : H6Elb2LBdxc // joke : What's blue and not very heavy? Light blue. // status : 200 

Please be aware that for. of loops will iterate over the entire prototype chain, so here we’re using hasOwnProperty to ensure that the property belongs to our res object.

Use Object.entries , Object.values or Object.entries

An alternative approach to above is to use one of Object.keys(), Object.values() or Object.entries(). These will return an array which we can then iterate over.

Let’s take a look at using Object.entries . This returns an array of the key/value pairs of the object we pass it:

const res = JSON.parse(xhr.responseText); Object.entries(res).forEach((entry) =>  const [key, value] = entry; console.log(`$key>: $value>`); >); // id: SvzIBAQS0Dd // joke: What did the pirate say on his 80th birthday? Aye Matey! // status: 200 

Note that the const Foreach for json javascript = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.

This is much more concise, avoids the aforementioned prototype problem, and is my preferred method of looping through a JSON response.

Using the Fetch API

While the method above using the XMLHttpRequest object works just fine, it can get unwieldy pretty quickly. We can do better.

The Fetch API is a Promise-based API, which enables a cleaner, more concise syntax and helps keep you out of callback hell. It provides a fetch() method defined on the window object, which you can use to perform requests. This method returns a Promise that you can use to retrieve the response of the request.

Let’s rewrite our previous example to use it:

(async () =>  const res = await fetch('https://icanhazdadjoke.com/',  headers:  Accept: 'application/json' >, >); const json = await res.json(); Object.entries(json).forEach(([key, value]) =>  console.log(`$key>: $value>`); >); >)(); // id: 2wkykjyIYDd // joke: What did the traffic light say to the car as it passed? "Don't look I'm changing!" // status: 200 

The Fetch API returns a response stream. This is not JSON, so instead of trying to call JSON.parse() on it, we’ll need to use its response.json() function. This returns a Promise that resolves with the result of parsing the response’s body text as JSON.

Dealing with an Array

As mentioned at the top of the article, an ordered list of values (aka an array), is valid JSON, so before we finish, let’s examine how to deal with such a response.

For the final example, we’ll use GitHub’s REST API to get a list of a user’s repositories:

(async () =>  async function getRepos(username)  const url = `https://api.github.com/users/$username>/repos`; const response = await fetch(url); const repositories = await response.json(); return repositories; > const repos = await getRepos('jameshibbard'); console.log(repos); >)(); // Array(30) [ , , , , , , , , , , … ] 

As you can see, the API has returned an array of objects. To access each of the individual objects, we can use a regular forEach method:

repos.forEach((repo) =>  console.log(` has $repo.stargazers_count> stars`); >); // Advanced-React has 0 stars // angular2-education has 0 stars // aurelia-reddit-client has 3 stars // authentication-with-devise-and-cancancan has 20 stars // . 

Alternatively, you can of course use any of the methods discussed above to loop through all of the object’s properties and log them to the console:

repos.forEach((repo) =>  Object.entries(repo).forEach(([key, value]) =>  console.log(`$key>: $value>`); >); >); // name: Advanced-React // full_name: jameshibbard/Advanced-React // private: false // . 

Conclusion

In this quick tip, we’ve looked at what JSON is. I’ve demonstrated how to parse a JSON response from a server into a native data structure (such as an array or an object), and how to loop through such a structure, so as to access the data it contains.

If you’re having trouble with anything presented in this article, why not stop by SitePoint’s Forums, where there are plenty of friendly people to help you out.

Share This Article

Network admin, freelance web developer and editor at SitePoint.

Источник

Looping over JSON array in JavaScript

JSON forEach tutorial shows how to loop over a JSON array in JavaScript. In this article we use JSON server to handle test data.

The is a JavaScript library to create testing REST API.

First, we create a project directory an install the json-server module.

$ mkdir jsonforeach $ cd jsonforeach $ npm init -y $ npm i -g json-server

The JSON server module is installed globally with npm .

JSON test data

We have some JSON test data:

$ json-server --watch users.json

The —watch command is used to specify the data for the server.

With the curl command, we get the user with Id 3.

JSON forEach example

In the next example we retrieve data with a GET request using fetch API. We loop over the returned data with forEach .

This is the index.html page. By clicking on the Log button, we fetch the data from the JSON server test data and log it into the browser console.

const logBtn = document.getElementById('log'); logBtn.addEventListener('click', fetchData); async function fetchData() < const response = await fetch('http://localhost:3000/users/'); const data = await response.json(); data.forEach(obj => < Object.entries(obj).forEach((Foreach for json javascript) => < console.log(`$$`); >); console.log('-------------------'); >); >

The fetch function retrieves data as JSON array from the provided URL. With forEach , we go through the array.

Object.entries(obj).forEach((Foreach for json javascript) => < console.log(`$$`); >);

We go over the entries of each object and print the key and the value to the console.

id 1 main.js:12:13 first_name Robert main.js:12:13 last_name Schwartz main.js:12:13 email rob23@gmail.com main.js:12:13 ------------------- main.js:14:9 id 2 main.js:12:13 first_name Lucy main.js:12:13 last_name Ballmer main.js:12:13 email lucyb56@gmail.com main.js:12:13 ------------------- main.js:14:9 .

This is the output in the browser console.

In this article we have shown how to iterate over a JSON array with forEach.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

Источник

How to Iterate Through JSON Objects in JavaScript

Use for … in . It’s fast. It’s clean. It looks nice.

for (let key in obj) < let value = objForeach for json javascript; if (obj.hasOwnProperty(key)) < console.log(`Property $key> is NOT from prototype chain`); > else < console.log(`Property $key> is from prototype chain`); > > 

Not Quite TL;DR

We can’t exactly “iterate” through an object like we can an array since it has no defined order. So, what do we do?

Suppose we have the following object:

// Example object let obj = < key1: "val1", key2: "val2", key3: "val3" > 

We’ll go over a few ways JavaScript allows us to “iterate” through JSON objects.

Method 1: .entries()

We can use Object.entries() to convert a JSON array to an iterable array of keys and values.

Object.entries(obj) will return an iterable multidimensional array.

[ ["key1", "val1"], ["key2", "val2"], ["key3", "val3"], ] 

We can use this output to find our keys and values in a bunch of different ways.

for (let Foreach for json javascript of Object.entries(obj))
Object.entries(obj).forEach(entry => < let key = entry[0]; let value = entry[1]; console.log(key, value); >); 
Object.entries(obj).map(entry => < let key = entry[0]; let value = entry[1]; console.log(key, value); >); 

Method 2: .keys()

Similarly, Object.keys(obj) returns an iterable list of keys.

Object.getOwnPropertyNames() is another way to access an object’s keys.

It’s essentially the same as Object.keys() .

Object.keys(obj).forEach(key => < let value = objForeach for json javascript; console.log(key, value); >); 

Method 3: .values()

Similarly, Object.values(obj) returns an iterable list of values.

In this instance, we won’t have access to the key associated with each value .

Object.values(obj).forEach(value => < console.log(value); >); 

Method 4: for … in

for (let key in obj) < let value = objForeach for json javascript; console.log(key, value); > 

You can also make an optional check for properties in the prototype chain to avoid logging inherited properties.

for (let key in obj) < let value = objForeach for json javascript; if (obj.hasOwnProperty(key)) < console.log(`Property $key> is NOT from prototype chain`); > else < console.log(`Property $key> is from prototype chain`); > > 

We won’t need to check hasOwnProperty() if we’re using a simple object, or one we made ourselves with <> .

Which Method is the Fastest?

We’re going to run each method 10,000,000 times to compare performance at a higher scale.

We’ll be using console.time() to track the time it takes each method to run 10 million times.

function runTest(fn, name, n = 10000000) < console.time(name); for(let i = 0; i  n; i++) < fn(); >console.timeEnd(name); > 

Here, we’re defining a function for each method we described above.

function method1_1() < for (let Foreach for json javascript of Object.entries(obj)) < >> function method1_2() < Object.entries(obj).forEach(entry => < let key = entry[0]; let value = entry[1]; >); > function method1_3() < Object.entries(obj).map(entry => < let key = entry[0]; let value = entry[1]; >); > function method2() < Object.keys(obj).forEach(key => < let value = objForeach for json javascript; >); > function method3() < Object.values(obj).forEach(value => < >); > function method4() < for (let key in obj) < let value = objForeach for json javascript; > > 
runTest(method1_1, "Method 1.1") runTest(method1_2, "Method 1.2") runTest(method1_3, "Method 1.3") runTest(method2, "Method 2") runTest(method3, "Method 3") runTest(method4, "Method 4") 

Here are the results, from fastest to slowest.

"Method 3": .values(): 946.156982421875ms "Method 4": for . in: 1364.801025390625ms "Method 2": .keys(): 1504.135009765625ms "Method 1.2": .entries(): 11261.76171875ms "Method 1.1": .entries(): 11572.80419921875ms "Method 1.3": .entries(): 11719.972900390625ms 

Method 3 only has access to the values , so it never performs any extra computation to obtain the key . This is why it’s the “fastest” method.

For methods that do have access to both the key and value of an object, Method 4 appears to be the fastest.

Conclusion

It seems that the for … in method is the fastest (and, in my opinion, the cleanest) method for iterating through a JSON object.

Keep in mind that object properties are not stored in any order, so when we iterate over an object, we can’t guarantee any order in which they will appear.

Источник

Читайте также:  Система управления html страницами
Оцените статью