Borislav Hadzhiev
Thu Nov 04 2021·2 min read
Photo by Casey Callahan
To loop through an object in reverse order, use the Object.keys()
method to
get an array of the object's keys and call the reverse()
method to reverse the
array. You can then iterate over the array using the forEach()
method and
access the object's keys and values in reverse order.
const obj = { a: 'one', b: 'two', c: 'three', }; // 👇️ ['c', 'b', 'a'] const reversedKeys = Object.keys(obj).reverse(); reversedKeys.forEach(key => { console.log(key, obj[key]); // 👉️ c three, b two, a one });
The first step is to get an array of the object's keys by using the Object.keys method.
const obj = { a: 'one', b: 'two', c: 'three', }; const keys = Object.keys(obj); console.log(keys); // 👉️ ['a', 'b','c']
Object.keys()
method returns the keys ordered in the same way as given by looping over the object properties manually.To reverse the keys array, we use the Array.reverse method.
The reverse()
method reverses the elements in the array in place and returns
the result.
const obj = { a: 'one', b: 'two', c: 'three', }; const keys = Object.keys(obj); console.log(keys); // 👉️ ['a', 'b','c'] const reversed = keys.reverse(); console.log(reversed); // 👉️ ['c', 'b', 'a']
reverse()
method changes the contents of the original array.const arr = ['a', 'b', 'c']; const reversed = arr.reverse(); console.log(reversed); // 👉️ ['c', 'b', 'a'] console.log(arr); // 👉️ ['c', 'b', 'a']
To circumvent mutating the original array, you will often have to create a copy
before calling the reverse()
method.
const arr = ['a', 'b', 'c']; const reversed = [...arr].reverse(); console.log(reversed); // 👉️ ['c', 'b', 'a'] console.log(arr); // 👉️ ['a', 'b', 'c']
The last step is to use the Array.forEach method to iterate over the reversed array of keys.
Here's the complete example:
const obj = { a: 'one', b: 'two', c: 'three', }; const reversedKeys = Object.keys(obj).reverse(); reversedKeys.forEach(key => { console.log(key, obj[key]); // 👉️ c three, b two, a one });