Get last item of nested object - Javascript Object

Javascript examples for Object:Object Property

Description

Get last item of nested object

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
window.onload=function(){/* w w  w.  j  a  v  a 2 s .  c  om*/
    let myObject = {
      levelOne: {
        levelTwo: {
          levelThree: 1
        }
      }
    };
    function getLast(object){
      if (typeof object !== 'object'){
        return object;
      }
      for ( prop in object){
        return getLast(object[prop])
      }
    }
    console.log(getLast(myObject));
}

      </script> 
   </head> 
   <body>  
   </body>
</html>

Related Tutorials