Borislav Hadzhiev
Fri Nov 12 2021·2 min read
Photo by Artem Kovalev
To get the last item in an object, use the Object.keys()
method to get an
array of the object's keys and call the pop()
method on the result, e.g.
Object.keys(obj).pop()
. The pop()
method will return the last key in the
object.
const obj = {one: 1, two: 2, three: 3}; const lastKey = Object.keys(obj).pop(); console.log(lastKey); // 👉️ three const lastValue = Object.values(obj).pop(); console.log(lastValue); // 👉️ 3
We used the Object.keys method to get an array of the object's keys.
const obj = {one: 1, two: 2, three: 3}; // 👇️ ['one', 'two', 'three'] console.log(Object.keys(obj));
The last step is to use the Array.pop method, which removes the last element from an array and returns it.
// 👇️ "three" console.log(Object.keys(obj).pop());
pop()
method changes the array on which it's called, however this is irrelevant in our scenario because we use the array of keys as a throwaway array.You can get the value that corresponds to the key by accessing the object at the specific key.
const obj = {one: 1, two: 2, three: 3}; const lastKey = Object.keys(obj).pop(); console.log(lastKey); // 👉️ three const v = obj[lastKey]; console.log(v); // 👉️ 3
We used bracket notation to access the value that's associated to the property.
You can access the last value in an object directly, by using the
Object.values()
method to get an array of the object's values and calling the
pop()
method on the result, e.g. Object.values(obj).pop()
.
const obj = {one: 1, two: 2, three: 3}; const lastValue = Object.values(obj).pop(); console.log(lastValue); // 3
The
Object.values
method returns an array containing the object's values, on which we can use the
pop()
method to get the last value.
An alternative approach is to use the Object.entries method, which returns an array containing key-value pair sub-arrays.
const obj = {one: 1, two: 2, three: 3}; const [key, value] = Object.entries(obj).pop(); console.log(key); // 👉️ three console.log(value); // 👉️ 3
The Object.entries()
method returns a two dimensional array.
// 👇️ [['one', 1], ['two', 2], ['three', 3]] console.log(Object.entries(obj));
We used the pop()
method to get the last sub-array that contains a key-value
pair.
The last step is to use
destructuring assignment
to assign the first and second array elements to the key
and value
variables.
const [key, value] = ['three', 3]; console.log(key); // 👉️ three console.log(value); // 👉️ 3
An easy way to think about destructuring assignment is - we're assigning the array elements to variables. Note that the order of assignment is preserved.