How To Loop Through Object In Reverse Order Using JavaScript

Loop through Object in Reverse Order using JavaScript

To loop through object in reverse order using JavaScript, I will use some built-in methods like keys() and reverse(). In this article, I will help you understand and implement it through a few examples. Let’s learn it below.

Loop through object in reverse order using JavaScript

Before looping through object in reverse order, we must get the list of properties of the object. To do this, I will use the keys() method to get the object’s properties.

keys() method

Syntax:

Object.keys(obj)

Parameter:

  • obj: The object you want to get the properties from.

Example:

var obj = {
	"Property1": "value1",
	"Property2": "value2",
	"Property3": "value3"
};

var arrProperty = Object.keys(obj);
console.log(arrProperty);

Output:

(3) ['Property1', 'Property2', 'Property3']

After obtaining the object’s keys, we will loop through the object in reverse order in two ways below.

Use For loop

The For loop can help us iterate through every element of an array to output the elements we want so that we can use it to loop through the object in reverse order. I will do it like this:

var obj = {
	"Property1": "value1",
	"Property2": "value2",
	"Property3": "value3"
};

// Get all keys in the obj
var arrProperty = Object.keys(obj);

// Loop through object in reverse order
for (let index = arrProperty.length - 1; index >= 0; index--) {
	console.log(arrProperty[index] + ": " + obj[arrProperty[index]]);
}

Output:

Property3: value3
Property2: value2
Property1: value1

We can set the starting point and the condition of the For loop. We will get a list of properties of the object whose list has been reversed.

Use the reverse() method

reverse() method returns a new array with the number of elements reversed from the original array. We can use it to iterate over the properties of the reversed object.

Syntax:

array.reverse()

Example:

var obj = {
	"Property1": "value1",
	"Property2": "value2",
	"Property3": "value3"
};

// Get all keys in obj and reverse it
var arrProperty = Object.keys(obj).reverse();

for (let index = 0; index < arrProperty.length; index++) {
	console.log(arrProperty[index] + ": " + obj[arrProperty[index]]);
}

Output:

Property3: value3
Property2: value2
Property1: value1

In using the reverse() method, you see, I also use For loop, but I don’t use it to invert an array of properties. I used the reverse() method and only used the For loop to output keys/values of obj’s properties.

Summary

Above are two ways to loop through object in reverse order using JavaScript. The first way is using the For loop because it doesn’t require us much, just set the condition to make the loop accurate and easier to understand when we read our code. Hope the article helps you and your program. Wish you success!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *