Introduction
In this lab, we will explore how to iterate over an object's own properties in reverse order using JavaScript. We will use built-in methods such as Object.keys() and Array.prototype.reverse() to achieve this. By the end of this lab, you will have a better understanding of how to work with objects in JavaScript and how to manipulate their properties.
Here's how to iterate over an object's own properties in reverse
To iterate over an object's own properties in reverse order and run a callback for each one, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Object.keys()to get all the properties of the object. - Use
Array.prototype.reverse()to reverse the order of the properties. - Use
Array.prototype.forEach()to run the provided function for each key-value pair. - The callback function should have three arguments: the value, the key, and the object.
Here's the code:
const forOwnRight = (obj, fn) =>
Object.keys(obj)
.reverse()
.forEach((key) => fn(obj[key], key, obj));
You can use this function with any object and callback function. For example, to log the values of { foo: 'bar', a: 1 } in reverse order, you can use the following code:
forOwnRight({ foo: "bar", a: 1 }, (v) => console.log(v)); // 1, 'bar'
Summary
Congratulations! You have completed the Iterate Over Object's Own Properties in Reverse lab. You can practice more labs in LabEx to improve your skills.