How do I check if an array includes an object in JavaScript?

JavascriptWeb DevelopmentFront End Technology

With JavaScript, try to run the following code to check whether an array includes an object or not. Here, “true” will be returned to finding the specific object in the array −

Example

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <script>
         var book = [ {
            Name: 'Java',
               ID: '001'
         }, {
            Name: 'Ruby', ID: '002'
         }];
         var result = false;
         for(var i = 0; i < book.length; i++) {
            if (book[i].Name == 'Ruby') {
               result = true;
               document.write(result.toString());
               break;
            }
         }
      </script>
   </body>
</html>

Output

true
raja
Published on 03-Feb-2018 13:34:50
Advertisements