Javascript Data Type How to - Find a value in an array of objects








Question

We would like to know how to find a value in an array of objects.

Answer


<!DOCTYPE html>
<html>
<head>
</head><!--   w w w.jav  a 2 s  .c o  m-->
<body>
  <script type='text/javascript'>
var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];
var obj = array.filter(function ( obj ) {
    return obj.name === 'string 1';
})[0];
document.writeln( JSON.stringify(obj) );

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

The code above is rendered as follows: