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.
Get the Last Item in a JavaScript Object
To get the last item in a JavaScript object, we can use the Object.entries
method to get the key-value pair arrays of an object in an array.
Therefore, we can use it to get the last item of the JavaScript object.
For instance, we can write:
const obj = {
'a': 'apple',
'b': 'banana',
'c': 'carrot'
}
const entries = Object.entries(obj)
const [last] = entries.slice(-1)
console.log(last)
We have the obj
object that we want to get the last property from.
Next, we call Object.entries
with obj
to get an array of key-value pair arrays of obj
.
Then we call slice
with -1 to return an array with the last entry of entries
.
And we destructure that and assign it to last
.
Therefore, last
is:
["c", "carrot"]
Conclusion
To get the last item in a JavaScript object, we can use the Object.entries
method to get the key-value pair arrays of an object in an array.
Therefore, we can use it to get the last item of the JavaScript object.