Javascript json list for

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((Javascript json list for) => < 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((Javascript json list for) => < 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 = objJavascript json list for; 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 Javascript json list for 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 = objJavascript json list for; 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 = objJavascript json list for; 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 = objJavascript json list for; 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 Javascript json list for 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 = objJavascript json list for; >); > function method3() < Object.values(obj).forEach(value => < >); > function method4() < for (let key in obj) < let value = objJavascript json list for; > > 
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.

Источник

Create Lists From JSON Data in Javascript (Simple Examples)

Welcome to a quick tutorial on how to create HTML lists from JSON data in Javascript. Want to dynamically generate a list from JSON data?

  1. Parse the JSON data into an array first (assuming it is a flat array) – var data = JSON.parse(DATA);
  2. Loop through the array and create the HTML list.
  3. var list = document.createElement(«ul»);
  4. for (let i of data)
  5. Lastly, append the list to where you want – document.getElementById(ID).appendChild(list);

That should cover the basics, but read on for more examples!

TLDR – QUICK SLIDES

Create Lists From JSON Data in Javascript

TABLE OF CONTENTS

HTML LIST FROM JSON DATA

All right, let us now get into the examples of how to create an HTML list from JSON data.

1) CREATE ELEMENT

    
  • We use JSON.parse() to turn the JSON string back into an array.
  • Create the HTML list using document.createElement(«ol») .
  • Then loop through the array, append the list items – for (let i of data) < . document.createElement("li") . >.
  • Lastly, add the list to where it is required – document.getElementById(TARGET).appendChild(list) .

2) MANUAL HTML STRING

Don’t like the “object-oriented” way of using createElement() and appendChild() ? This is an alternative, where we create an HTML string instead.

3) NESTED OBJECTS & LISTS

    

Lastly, what if we have a nested object? Keep calm and look carefully, we are pretty much doing the same. Parse the JSON data into an object, then loop through the nested object to create a nested list.

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

SUPPORT

600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment Cancel Reply

Breakthrough Javascript

Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

Socials

About Me

W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

Источник

Читайте также:  Php charset conversion from
Оцените статью