Categories
JavaScript Answers

How to get the last item in a JavaScript object with a for loop?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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