Saturday, January 31, 2026
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
32478 POSTS0 COMMENTS
Milvus
122 POSTS0 COMMENTS
Nango Kala
6849 POSTS0 COMMENTS
Nicole Veronica
11978 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12066 POSTS0 COMMENTS
Shaida Kate Naidoo
6987 POSTS0 COMMENTS
Ted Musemwa
7222 POSTS0 COMMENTS
Thapelo Manthata
6934 POSTS0 COMMENTS
Umr Jansen
6917 POSTS0 COMMENTS