Open In App

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:



Example: This example implements the above approach. 




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:

Example: This example implements the above approach. 




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'




Article Tags :