0
votes

I'm trying to filter my array with data in Vue.js. I do it in computed property. This is the test array:

{
    "Animals": [
        {
            "date_time": "2011.08.31",
            "animal_list": [
                {
                    "animal_title": "Monkey"
                },
                {
                    "animal_title": "Giraffe"
                }
            ]
        },
        {
            "date_time": "2012.08.31",
            "animal_list": [
                {
                    "animal_title": "Raccoon"
                },
                {
                    "animal_title": "Giraffe"
                }
            ]
        }
    ]
}

And this is my filter function:

filteredData.filter(item =>
        item.animal_list.some(
          elem =>
            elem.animal_title
              .toLowerCase()
              .indexOf(this.animalTitle.toLowerCase()) != -1
        )
      );

It seems good, but doesn't work. When I enter "Raccoon" in the form, it must return only second object, but it returns all objects.

Why does it happen? What am I doing wrong?

UPD: filteredData is an Array. filteredData = animalData.Animals

1
My guess is that this.animalTitle is an empty string when you run the filter. Put a breakpoint and see.Jonathan
Check the value of this.animalTitleAnurag Srivastava
@Jonathan, No, I watched in console. There is "false" for the first object, and "true" for second. But it doesn't filter anyway.Shadowman
You should always use triple equals instead of !=, for example !==. When using triple equals === in JavaScript, we are testing for strict equality. This means both the type and the value we are comparing have to be the same.KennyDope
@KennyDope It was never a problem for me before this issue. But ok, I changed it...and nothing happened(Shadowman

1 Answers

1
votes

Tried to reproduce your question, but in my fiddle it is working as expected:

const data = {
    "Animals": [
        {
            "date_time": "2011.08.31",
            "animal_list": [
                {
                    "animal_title": "Monkey"
                },
                {
                    "animal_title": "Giraffe"
                }
            ]
        },
        {
            "date_time": "2012.08.31",
            "animal_list": [
                {
                    "animal_title": "Raccoon"
                },
                {
                    "animal_title": "Giraffe"
                }
            ]
        }
    ]
};

const filtering = () => {
  const filteredData = data.Animals;
  const animalTitle = "Giraffe";

    return filteredData.filter(
        item => item.animal_list.some(
        elem => elem.animal_title.toLowerCase().indexOf(animalTitle.toLowerCase()) !== -1)
    );
}

const result = filtering();
console.log(result);

https://jsfiddle.net/Kenvdb/tq5zk79w/

** UPDATE ** Changed the Fiddle to Vue JS component to illustrate solution.