Search code examples
javascriptecmascript-6javascript-objectsangularjs-filter

this Javascript code gives output as [object, Object] , instead of [f, dog]


this Javascript code gives output as [object, Object] , instead of [f, dog].??

 <html>
     <body>
      <button onclick="myFunction()">Try it</button>
      <p id="demo"></p>
       <script>
        var animals = [{name:'f', species :'dog'},{name:'f1', species :'dog1'}];
        function isSog(animal) {

            if(animal.species==='dog') return animal;
        }
        function myFunction() {
            document.getElementById("demo").innerHTML = animals.filter(isSog);
        }
       </script>
      </body>
    </html>

Solution

  • You need to convert array that you get (after filter method) into string before assigning to innerHTML. So as an example below I am calling JSON.stringify.

    You can do :

    document.getElementById("demo").innerHTML = JSON.stringify(animals.filter(isSog));
    

    Or you can choose any other format you want. You will have to do some further processing on returned array.

    For a simple case such as yours, you can do following:

    var animals = [{
      name: 'f',
      species: 'dog'
    }, {
      name: 'f1',
      species: 'dog1'
    }];
    
    function isSog(animal) {
    
      if (animal.species === 'dog') return animal;
    }
    
    var retObj = animals.filter(isSog);
    document.getElementById("demo").innerHTML = "[" + retObj[0].name + "," + retObj[0].species + "]";
    <p id="demo"></p>

    Note that if your returned array is larger, looping and creating a string would be right option.