简体   繁体   中英

Data filtering Javascript (Nested dictionary and arrays)

I`m trying to figure out how js filter() works.

I have an API, which returns something like this:

[
    {
        "name": "Category 1",
        "items": [
            {
                "name": "Vacancy item #1",
                "location": "Los Angeles",
                "overview": "Lorem ipsum",
                "get_absolute_url": "/careers/vacancy-item-1/"
            },
            {
                "name": "Vacancy item #2",
                "location": "Los Angeles",
                "overview": "Lorem ipsum",
                "get_absolute_url": "/careers/vacancy-item-2/"
            }
        ]
    },
    {
        "name": "Category 2",
        "items": [
            {
                "name": "Vacancy item #3",
                "location": "Washington D.C",
                "overview": "Lorem ipsum",
                "get_absolute_url": "/careers/vacancy-item-3/"
            }
        ]
    }
]

I want to filter this data based on the select value of the form. I`m working on the VUE.JS and Django.

And this is my JS code

filteredItems() {
                let vacancycategories = this.listData,
                    city = this.city,
                    category = this.category


                if (city && city.length > 0) {
                    vacancycategories = vacancycategories.filter((cat) => {

                         cat.items = cat.items.filter((vacancy) => {
                            return vacancy.location.indexOf(city) !== -1
                        })
                            return cat
                    })
                } 

                if (category && category.length > 0) {
                    vacancycategories = vacancycategories.filter((cat) => {
                        return cat.name.indexOf(category) !== -1
                    })
                }  
                return vacancycategories
            }

The category part is working as expected. But when I try to filter location fields, it's not working properly. The first selected option works normal but then when you select another option it returns an empty list.

every filter function need to return the boolean value.
Inner filter function is fine, But the outer filter function need to change. Following changes should work.

vacancycategories = vacancycategories.filter(cat => {
  return (
    cat.items.filter(vacancy => {
      return vacancy.location.indexOf(city) !== -1;
    }).length > 0
  );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM