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'