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. Lets 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.
This is just a basic React set up to fetch data from API using Axios. For more detail, you can visit this tutorial. 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
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.
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.
Synatx
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Example
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)
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
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
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
Lodash _.forEach
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(array, function(value) {
console.log(value);
});
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);
});
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 lets 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
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
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
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
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
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 invokesiteratee
for each element. The iteratee is invoked with three arguments: (value, index|key, collection). Iteratee functions may exit iteration early by explicitly returningfalse
.
Syntax
_.forEach(Object, function(value, key) {
console.log(value);
});
Example
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
thruiteratee
. The iteratee is invoked with three arguments:(value, index|key, collection).
Syntax
_.map(Object, function(value, key) {
console.log(value);
});
Example
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 in the comment section Until then check the live example and GitHub repository for practice.