Thursday, October 23, 2025
HomeLanguagesJavascriptHow to get the last item of JavaScript object ?

How to get the last item of JavaScript object ?

In this article, we will learn how to get the last item of a Javascript object. Given a JavaScript object and the task is to get the last element of the JavaScript object. This can be done by the following methods:

Approach 1:

  • Use Object.keys() method to get the all keys of the object.
  • Now use indexing to access the last element of the JavaScript object.

Example: This example implements the above approach. 

Javascript




let Obj = {
    "1_prop": "1_Val",
    "2_prop": "2_Val",
    "3_prop": "3_Val"
};
 
console.log(JSON.stringify(Obj));
function GFG_Fun() {
    console.log("The last key = '" +
        Object.keys(Obj)[Object.keys(Obj).length - 1]
        + "' Value = '"
        + Obj[Object.keys(Obj)[Object.keys(Obj).length - 1]]
        + "'");
}
GFG_Fun()


Output

{"1_prop":"1_Val","2_prop":"2_Val","3_prop":"3_Val"}
The last key = '3_prop' Value = '3_Val'



Approach 2:

  • Use for loop to access all keys of the object and at the end of the loop, the loop variable will have the last key of the object.
  • Now use indexing to access the last element’s value of the JavaScript object.

Example: This example implements the above approach. 

Javascript




let Obj = {
    "1_prop": "1_Val",
    "2_prop": "2_Val",
    "3_prop": "3_Val"
};
 
console.log(JSON.stringify(Obj));
 
function GFG_Fun() {
    let lastElement;
 
    for (lastElement in Obj);
    lastElement;
 
    console.log("The last key = '" +
        lastElement + "' <br> Value = '"
        + Obj[lastElement] + "'");
}
GFG_Fun()


Output

{"1_prop":"1_Val","2_prop":"2_Val","3_prop":"3_Val"}
The last key = '3_prop' <br> Value = '3_Val'



RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS