Sometimes, we want to get the last item in a JavaScript object with a for loop.
In this article, we’ll look at how to get the last item in a JavaScript object with a for loop.
How to get the last item in a JavaScript object with a for loop?
To get the last item in a JavaScript object with a for loop, we can use the Object.entries
method.
For instance, we write:
const obj = {
foo: 1,
bar: 2,
baz: 3
}
const last = Object.entries(obj).at(-1)
console.log(last)
to call Object.entries
with obj
to return an array of key-value pair arrays from the object.
Then we call at
with -1 to return the last item in the array.
Therefore, last
is ['baz', 3]
.
Conclusion
To get the last item in a JavaScript object with a for loop, we can use the Object.entries
method.