Two Ways To Get The Last Item In An Object In JavaScript

Get the Last item in an Object in JavaScript

Some cases, we need to get the last item in an object in JavaScript. So how can we accomplish that? We have some solutions, such as accessing by key or converting an object to an array… Let’s find out below.

The solution to get the last item in an object in JavaScript

Get last item via Key

In this solution, we will use the final key to get the last item in an object in JavaScript if we already know the index. You can refer to the code below.

Example:

var animal = {
    item1 : 'dog',
    item2 : 'cat',
    item3 : 'bee'
}

console.log(animal.item3)

Output

bee

We can also get the last item through the Key in another way. You can refer to the below way.

Example:

var animal = {
    item1 : 'dog',
    item2 : 'cat',
    item3 : 'bee'
}

console.log(animal["item3"])

Output

bee

So, we got the last item in the animal object. However, this solution is only effective when we know the last Key of the object and the number of properties of the object is not much.

Convert the object’s values to an array

We can convert object values to an array using the Object.values() method. Then we quickly get the last value of the membrane, which is also the last item of the object. To learn more about this method, you can refer here.

Syntax

Object.values(obj)

Parameter

  • obj: is an object that we convert values into arrays.

This method will create a new array from the object’s values. The original object will not change.

Example:

var animal = {
    item1 : 'dog',
    item2 : 'cat',
    item3 : 'bee'
}

// Create a new array from the original values of the Object
var animalArray = Object.values(animal)

// Get last index
var lastIndex = animalArray.length - 1

// Show last item 
console.log(animalArray[lastIndex])

Output

bee

First, we must create a new array from the Object’s values. Then get the last index using the length property minus 1. And getting the last item is like getting the last element of an array. This solution is quite effective for objects with many properties that the programmer cannot remember all the order of the properties.

Summary

So we’ve learned some simple ways to get the last item in an object in JavaScript. We should get the last item via Key with simple objects and create an array of values with complex objects. We should consider using the appropriate solution depending on the problem.

Maybe you are interested:

Leave a Reply

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