Sometimes, we want to get the last item in a JavaScript object.
In this article, we’ll look at how to get the last item in a JavaScript object.
How to get the last item in a JavaScript object?
To get the last item in a JavaScript object, we can use the Object.values
method.
For instance, we write
const fruitValues = Object.values(fruitObject);
const last = fruitValues[fruitValues.length - 1];
to call Object.values
with the fruitObject
object to return an array of property values from fruitObject
.
Then we get the last value from the array with fruitValues[fruitValues.length - 1]
to get the last item in the fruitObject
object.
Conclusion
To get the last item in a JavaScript object, we can use the Object.values
method.