• Techblog369, India
  • September 29, 2022

How to create PHP QR code and Save it to Database?

Hi In this Article I am going to show how to create QR code and save it to database also fetch QR Code in a Table Create a Page addqrcode.php in …

How to Send Multiple Files Attachment Mail using Laravel

Hi in this article i am going to show how to send multiple files attachment mail in Laravel. It’s simple example of Laravel send multiple attachment in mail. I explained simply …

Different ways to loop through arrays and objects in React

If we are working on any React project we have to play with arrays and objects for data. Arrays are used to store multiple data into a single variable and objects are a collection of properties which is an association between a key and value. So both play an important role in the creation of an application. There are multiple ways to iterate through an array and object which we will see in this tutorial.

Array
To explain different ways to iterate array we will first set up a simple React app that will fetch data using Axios from our API. Let’s set up that.

  • Create React project yarn create react-app yourprojectname
  • Now install Axios yarn add axios
  • Paste the below code inside your project app.js file.

An array of data from API

This is just a basic React setup to fetch data from API using Axios. So we are logging out the response data we are getting from the API inside the getData function. Now I’ll show you how to iterate that array of data to our React project using the various approaches.

Javascript — map()

The map() method creates a new array with the result of calling a function for every array element.

Syntax

array.map(function(currentValue, index, arr), thisValue)

Example

import React, { Component } from 'react'
import axios from 'axios'

export default class javascriptMap extends Component {
   constructor(props){
       super(props)
       this.state = {
         data: []
       }
     }
   
     getData(){
       axios.get('http://jsonplaceholder.typicode.com/users').then(res => {
         var data = res.data
           this.setState({data : data})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
       return (
           <>
            <ul>
       {this.state.data.map(d => (<li key={d.id}>{d.name}</li>))} 
               </ul>
           </>
       )
   }
}

So after receiving the data from the API I have changed my data state from blank array to the response data using the React setState method. Now using the map function I am iterating the data inside the render method.

I have used the arrow function for a shorter version of my code you can also use the normal javascript function. Both will give the same result.

{this.state.data.map(function(d){
           return (
           <li key={d.id}>{d.name}</li>
           )
})} 

Javascript for Loop

The for loop is executed as long as a condition is true. It will continue to run as long as the condition is true. It will only stop when the condition becomes false

Syntax

for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Example

import React, { Component } from 'react'
import axios from 'axios'

export default class javascriptMap extends Component {
   constructor(props){
       super(props)
       this.state = {
         userName: ''
       }
     }
   
     getData(){
       axios.get('http://jsonplaceholder.typicode.com/users').then(res => {
           console.log(res.data)
         var data = res.data
         var loopData = ''
         var i ;
         for(i=0; i < data.length; i++){
             loopData += `<li>${data[i].name}</li>`
         }
         this.setState({userName: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {userName} = this.state
    console.log()
       return (
           <>
            
            <ul dangerouslySetInnerHTML={{__html: userName}}></ul>
             
           </>
       )
   }
}

After getting the data we are running a for loop to iterate data and passing the value to our blank variable (loopData). Now using the setState method we are changing our userName state from blank data to our new loopData. This will give us data in this.state.userName. After that using the Javascript destructuring method I am passing that to a single variable userName and then using React dangerouslySetInnerHTML={{__html: userName}} I am parsing our data which contains HTML elements.

Javascript forEach Loop

The forEach method executes a provided function once for each array element.

Syntax

array.forEach(function(currentValue, index, arr), thisValue)
import React, { Component } from 'react'
import axios from 'axios'

export default class javascriptForEachLoop extends Component {
   constructor(props){
       super(props)
       this.state = {
         userName: ''
       }
     }
   
     getData(){
       axios.get('http://jsonplaceholder.typicode.com/users').then(res => {
         var data = res.data
         var forEachData = ''
         data.forEach(d => forEachData += `<li>${d.name}</li>`)

         this.setState({userName: forEachData})
         
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
     const {userName} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: userName}}></ul>
           </>
       )
   }

This is like a combination of map function and for loop. Same after getting the data running a forEach loop to iterate our data and pushing data to the blank variable (forEachData) then changing the state of userName using the setState method, destructuring the userName, and then finally sending it to dangerouslySetInnerHTML for parsing the userName.

The old fashioned way

data.forEach(
  function(d){
    forEachData += '<li>' + d.name + '</li>'
   }
)

Javascript while Loop

while loop is executed while a specified condition is true. It will only stop when the condition becomes false.

Syntax

while (condition) {
// code block to be executed
}

Example

import React, { Component } from 'react'
import axios from 'axios'

export default class javascriptWhileLoop extends Component {
   constructor(props){
       super(props)
       this.state = {
         userName: ''
       }
     }
     getData(){
       axios.get('http://jsonplaceholder.typicode.com/users').then(res => {
         var data = res.data
         var loopData = ''
         var i = 0 ;
         while (i < data.length){
             loopData += `<li>${data[i].name}</li>`;
             i++;
         }
         this.setState({userName: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {userName} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: userName}}></ul>
           </>
       )
   }
}

This is similar to for loop just the syntax is different. So check the for loop above for detail.

Javascript Do While loop

The do/while loop executes a block of code once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax

do {
 code block to be executed
}
while (condition);

Example

import React, { Component } from 'react'
import axios from 'axios'

export default class javascriptDoWhileLoop extends Component {
   constructor(props){
       super(props)
       this.state = {
         userName: ''
       }
     }
     getData(){
       axios.get('http://jsonplaceholder.typicode.com/users').then(res => {
         var data = res.data
         var loopData = ''
         var i = 0 ;
         do {
           loopData += `<li>${data[i].name}</li>`;
           i++;
         }
         while (i < data.length); 
         this.setState({userName: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {userName} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: userName}}></ul>
           </>
       )
   }
}

Lodash _.forEach

Iterates over elements of the collection and invoke iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

Syntax

_.forEach(array, function(value) {
 console.log(value);
});

Example

import React, { Component } from 'react'
import axios from 'axios'
import _forEach from 'lodash/forEach'

export default class lodashforEach extends Component {
   constructor(props){
       super(props)
       this.state = {
         userName: ''
       }
     }
   
     getData(){
       axios.get('http://jsonplaceholder.typicode.com/users').then(res => {
         var data = res.data
         var forEachData = ''
         _forEach(data, d => forEachData += `<li>${d.name}</li>`)

         this.setState({userName: forEachData})
         
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
     const {userName} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: userName}}></ul>
           </>
       )
   }
}

Note: The _.each method of lodash will also give the same result. The syntax is also the same as _.forEach method.

Lodash _.map

Creates an array of values by running each element in collection thru iteratee. The iteratee is invoked with three arguments: (value, index|key, collection).

Syntax

_.map(array, function(value) {
console.log(value);
});

Example

import React, { Component } from 'react'
import axios from 'axios'
import _map from 'lodash/map'

export default class javascriptMap extends Component {
   constructor(props){
       super(props)
       this.state = {
         data: []
       }
     }
   
     getData(){
       axios.get('http://jsonplaceholder.typicode.com/users').then(res => {
         var data = res.data
           this.setState({data : data})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
     const {data} = this.state
       return (
           <>
            <ul>
       {_map(data, d => (<li key={d.id}>{d.name}</li>))} 
               </ul>
           </>
       )
   }
}

Object

Sometimes we have to loop through an object to get data. If we use map(), forEach() or for() it will give us TypeError: items is not iterable or function. So how do we loop through objects? let us see through the below examples.

After setting up the initial React project and calling data from the API using axios our object data will look something like this.

Now let’s loop through this object using different methods available.

Javascript for/in loop

The for/in loops through the properties of an object. The block of code inside the loop will be executed once for each property.

Syntax

for (var in object) {
 code block to be executed
}

Example

import React, { Component } from 'react'
import axios from 'axios'

export default class javascriptDoWhileLoop extends Component {
   constructor(props){
       super(props)
       this.state = {
         data: ''
       }
     }
     getData(){
       axios.get('https://jsonplaceholder.typicode.com/users/1').then(res => {
         var data = res.data
         var loopData = ''
         for(var x in data){
             if(x === 'name' ){
               loopData += `<h5>My name is ${data[x]}</h5>`
             }
           
         }
         this.setState({data: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {data} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: data}}></ul>
           </>
       )
   }
}

After getting data from the API I am using for/in loop to iterate our object. Inside for/in loop, the x contains the key of our object key-value pair, so I am checking that with javascript if statement that if x whose key is equal to the name should get the value of that key which in our case is Leanne Graham and after the check statement I am concating that value to loopData. Now after all this passing that loopData to our setState method to change the value of the data state. This will render us My name is Leanne Graham.

Javascript for/of loop

The for…of statement creates a loop iterating over iterable objects, including: built-in String, Array, array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables.

Syntax

for (variable of iterable) {
// code block to be executed
}

There are three ways we can use for/of loop to achieve our goal that’s to get only the name value from the object.

Example — Using Object.keys

import React, { Component } from 'react'
import axios from 'axios'

export default class javascriptObjectEntries extends Component {
   constructor(props){
       super(props)
       this.state = {
         data: ''
       }
     }
     getData(){
       axios.get('https://jsonplaceholder.typicode.com/users/1').then(res => {
         var data = res.data
         var loopData = ''
         for (var key of Object.keys(data)) {
           if(key === 'name'){
             loopData += `<h5>My name is ${data[key]}</h5>`
           }   
       }
       this.setState({data: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {data} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: data}}></ul>
           </>
       )
   }
}

Object.keys method returns an array of a given object’s own enumerable property names. Check below for an example.

const object = {
 a: 'Manish',
 b: 27,
 c: false
};
console.log(Object.keys(object));
// expected output: Array ["a", "b", "c"]

So Object.keys will give us the key of an object in an array. So now we have key and object, and running that inside for/of loop and passing our check statement we will get our desire result.

Example — Object.entries

import React, { Component } from 'react'
import axios from 'axios'

export default class javascriptObjectEntries extends Component {
   constructor(props){
       super(props)
       this.state = {
         data: ''
       }
     }
     getData(){
       axios.get('https://jsonplaceholder.typicode.com/users/1').then(res => {
         var data = res.data
         var loopData = ''
         for(let [key, value] of Object.entries(data)) {
           if(key === 'name'){
             loopData += `<h5>My name is ${value}</h5>`
           }
       }
       this.setState({data: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {data} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: data}}></ul>
           </>
       )
   }
}

The Object.entries() method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for…in loop.

const object = {
 a: 'Manish',
 b: 27
};
for (const [key, value] of Object.entries(object)) {
 console.log(`${key}: ${value}`);
}
// expected output:
// "a: Manish"
// "b: 27"
// order is not guaranteed

The above example is the combination of for…of, destructuring, if-else and Object.entries for getting our desire result.

Lodash ._forIn loop

Iterates over own and inherited enumerable string keyed properties of an object and invokes iteratee for each property. The iteratee is invoked with three arguments: (value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

Syntax

_.forIn(Object, function(value, key) {
 console.log(value);
});

Example

import React, { Component } from 'react'
import axios from 'axios'
import _forIn from 'lodash/forIn'

export default class lodashForIn extends Component {
   constructor(props){
       super(props)
       this.state = {
         data: ''
       }
     }
     getData(){
       axios.get('https://jsonplaceholder.typicode.com/users/1').then(res => {
         var data = res.data
         var loopData = ''
         _forIn(data, (value,key) => {
           if(key === 'name'){
             loopData += `<h5>My name is ${value}</h5>`
           }
         })
        
       this.setState({data: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {data} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: data}}></ul>
           </>
       )
   }
}

Lodash ._forOwn loop

Iterates over own enumerable string keyed properties of an object and invokes iteratee for each property. The iteratee is invoked with three arguments: (value, key, object). Iteratee functions may exit iteration early by explicitly returning false.

Syntax

_.forOwn(Object, function(value, key) {
 console.log(value);
});

Example

import React, { Component } from 'react'
import axios from 'axios'
import _forOwn from 'lodash/forOwn'

export default class lodashForOwnLoop extends Component {
   constructor(props){
       super(props)
       this.state = {
         data: ''
       }
     }
     getData(){
       axios.get('https://jsonplaceholder.typicode.com/users/1').then(res => {
         var data = res.data
         var loopData = ''
         _forOwn(data, (value,key) => {
           if(key === 'name'){
             loopData += `<h5>My name is ${value}</h5>`
           }
         })
        
       this.setState({data: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {data} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: data}}></ul>
           </>
       )
   }
}

Note: The syntaxes are same for lodash forIn and forOwn method but forIn iterates over own and inherited enumerable properties of an object while forOwn iterates over own enumerable string keyed properties. Both will work fine.

Lodash ._forEach loop

Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returning false.

Syntax

_.forEach(Object, function(value, key) {
 console.log(value);
});

Example

import React, { Component } from 'react'
import axios from 'axios'
import _forEach from 'lodash/forEach'

export default class lodashForEachLoop extends Component {
   constructor(props){
       super(props)
       this.state = {
         data: ''
       }
     }
     getData(){
       axios.get('https://jsonplaceholder.typicode.com/users/1').then(res => {
         var data = res.data
         var loopData = ''
         _forEach(data, (value,key) => {
           if(key === 'name'){
             loopData += `<h5>My name is ${value}</h5>`
           }
         })
        
       this.setState({data: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {data} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: data}}></ul>
           </>
       )
   }
}

Note Lodash ._forEach and its alias ._each is useful to loop through both objects and arrays

Lodash ._map

Creates an array of values by running each element in collection thru iteratee. The iteratee is invoked with three arguments:(value, index|key, collection).

Syntax

_.map(Object, function(value, key) {
 console.log(value);
});

Example

import React, { Component } from 'react'
import axios from 'axios'
import _map from 'lodash/map'

export default class lodashMap extends Component {
   constructor(props){
       super(props)
       this.state = {
         data: ''
       }
     }
     getData(){
       axios.get('https://jsonplaceholder.typicode.com/users/1').then(res => {
         var data = res.data
         var loopData = ''
         _map(data, (value,key) => {
           if(key === 'name'){
             loopData += `<h5>My name is ${value}</h5>`
           }
         })
        
       this.setState({data: loopData})
       })
     }
     componentDidMount(){
       this.getData()
     }
   render() {
    const {data} = this.state
       return (
           <>
            <ul dangerouslySetInnerHTML={{__html: data}}></ul>
           </>
       )
   }
}

So in the above examples, I have shown you all the possible ways available to loop through arrays and objects. If I have missed something please share it in the comment section

Author

admin@techblog369.in

Leave a Reply

Your email address will not be published.