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:
- Using Object.keys() method
- Using for loop method
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.
html
<!DOCTYPE html> < html lang = "en" > < head > < title >How to get the last item of JavaScript object</ title > </ head > < body > < h1 style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP1" > </ p > < p id = "GFG_UP2" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" > </ 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:

Get the last item of JavaScript object
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.
html
<!DOCTYPE html> < html lang = "en" > < head > < title >How to get the last item of JavaScript object</ title > </ head > < body > < h1 style = "color:green;" > GeeksforGeeks </ h1 > < p id = "GFG_UP1" > </ p > < p id = "GFG_UP2" > </ p > < button onclick = "GFG_Fun()" > click here </ button > < p id = "GFG_DOWN" > </ 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:

Get the last item of JavaScript object
Please Login to comment...