Skip to content
Related Articles
Open in App
Not now

Related Articles

How to get the last item of JavaScript object ?

Improve Article
Save Article
  • Last Updated : 04 Jan, 2023
Improve Article
Save Article

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. 

html




<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>


Output:

 Get the last item of JavaScript object

 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




<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>


Output:

 Get the last item of JavaScript object

 Get the last item of JavaScript object 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!