How to get the last item of JavaScript object ?
Given a JavaScript object and the task is to get the last element of the JavaScript object.
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.
<!DOCTYPE HTML> <html> <head> <title> How to get the last item of JavaScript object ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP1" style = "font-size: 15px; font-weight: bold;"> </p> <p id = "GFG_UP2" style = "font-size: 15px; font-weight: bold; color: green;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up1 = document.getElementById('GFG_UP1'); var up2 = document.getElementById('GFG_UP2'); var down = document.getElementById('GFG_DOWN'); var Obj = { "1_prop": "1_Val", "2_prop": "2_Val", "3_prop": "3_Val" }; up1.innerHTML = "Click on the button to get" + "the last element of the Object."; up2.innerHTML = JSON.stringify(Obj); function GFG_Fun() { down.innerHTML = "The last key = '" + Object.keys(Obj)[Object.keys(Obj).length-1] + "' <br> Value = '" + Obj[Object.keys(Obj)[Object.keys(Obj).length-1]] + "'"; } </script> </body> </html> |
Output:
- Before clicking on the button:

- After clicking on the button:

Approach 2:
- Use for loop to access the all keys of the object and at the end of the loop, 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.
<!DOCTYPE HTML> <html> <head> <title> How to get the last item of JavaScript object ? </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksforGeeks </h1> <p id = "GFG_UP1" style = "font-size: 15px; font-weight: bold;"> </p> <p id = "GFG_UP2" style = "font-size: 15px; font-weight: bold; color: green;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var up1 = document.getElementById('GFG_UP1'); var up2 = document.getElementById('GFG_UP2'); var down = document.getElementById('GFG_DOWN'); var Obj = { "1_prop": "1_Val", "2_prop": "2_Val", "3_prop": "3_Val" }; up1.innerHTML = "Click on the button to get" + "the last element of the Object."; up2.innerHTML = JSON.stringify(Obj); function GFG_Fun() { var lastElement; for (lastElement in Obj); lastElement; down.innerHTML = "The last key = '" + lastElement + "' <br> Value = '" + Obj[lastElement] + "'"; } </script> </body> </html> |
Output:
- Before clicking on the button:

- After clicking on the button:



