Finding one object inside JSON by its ID with array filter function - Javascript JSon

Javascript examples for JSon:JSon Convert

Description

Finding one object inside JSON by its ID with array filter function

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(){/*from  w w w. j  ava  2 s .c o  m*/
var arr = [
    {"ID":"5","Name":"Test"},
    {"ID":"30","Name":"Sharon"},
    {"ID":"40","Name":"Sharon"},
    {"ID":"50","Name":"Sharon"},
    {"ID":"32","Name":"ABC"}
];
function getById(arr, id) {
   return arr.filter(function(o) { return o.ID == id });
}
console.log( getById(arr, '30')[0].Name )
console.log( getById(arr, '32')[0].Name )
    }

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

Related Tutorials