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:
- Using Object.keys() method
- Using for loopmethod
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() |
{"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() |
{"1_prop":"1_Val","2_prop":"2_Val","3_prop":"3_Val"}
The last key = '3_prop' <br> Value = '3_Val'
