Find object by id in an array of JavaScript objects - Javascript jQuery

Javascript examples for jQuery:Array

Description

Find object by id in an array of JavaScript objects

Demo Code

ResultView the demo in separate window

<html>
 <head> 
  <meta name="viewport" content="width=device-width, initial-scale=1"> 
  <script type="text/javascript" src="https://code.jquery.com/jquery-1.6.3.js"></script> 
  <script type="text/javascript">
    $(window).load(function(){/*ww w  .  j  a  v  a  2 s.com*/
myArray = [{'id':'3','foo':'bar'},{'id':'4','foo':'bar'}];
var found = $.map(myArray, function(val) {
    return val.id == '45' ? val.foo : null;
});
console.log(found.length + "\n" + found[0]);
    });

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

Related Tutorials