A
A
anton_trofimov952020-01-29 22:03:47
Vue.js
anton_trofimov95, 2020-01-29 22:03:47

Can't filter JSON in Vue?

There is a working filter, I made it with a regular array - Link
I'm trying to do the same with JSON format, below is the code

<div id="app">
        <h1>Рейтинг участников:</h1>
        <div v-for="item in filteredList" :key="item.Id">
            <span>{{item.id}}</span>
            <span>{{item.name}}</span>
            <span>{{item.secondName}}</span>
            <span>Возраст: {{item.age}}</span>
            <span>Рейтинг: {{item.rating}}</span>
        </div>
        <p>Поиск по имени <input type="text" v-model="userName" /></p>
        <p><input type='checkbox' @change="sortAgeMethod" v-model="sortAge" />
            <label>Отсортировать по возрасту</label></p>
    </div>

var app = new Vue({
    el: '#app',
    data: {
        userName: '',
        sortAge: false,
        info: []
    },
    methods: {
        sortAgeMethod() {
            this.info.sort((a, b) => {
                if (this.sortAge) {
                    return b.age - a.age
                } else {
                    return a.age - b.age
                }
            })
        }
    },
    computed: {
        filteredList() {
            return this.info.filter(elem => elem.userName.toLowerCase().indexOf(this.userName.toLowerCase()) !== -1)
        }
    },
    mounted() {
        axios
            .get('./users.json')
            .then(response => (this.info = response.data.users))
            .catch(e => {
                console.error(e)
            })
    }
});


When trying to draw in the console, it gives an error. If you output , then everything works (i.e. the JSON array is displayed on the screen, but we need something else). By the vue principle, you need to output exactly the computed filteredList property in order for the filter to be applied. As a result, I was inspired by the thought that I was not filtering the JSON format correctly, i.e. it must be filtered somehow differently, not like a regular array. Or maybe not. Can you suggest what is wrong or where to look? <div v-for="item in info" :key="item.Id">

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
NerVik, 2020-01-29
@anton_trofimov95

something tells me that you don't have a `userName` field in your JSON and instead of it in

filteredList() {
            return this.info.filter(elem => elem.userName.toLowerCase().indexOf(this.userName.toLowerCase()) !== -1)
        }

need to write
filteredList() {
            return this.info.filter(elem => elem.name.toLowerCase().indexOf(this.userName.toLowerCase()) !== -1)
        }

in any case, I draw this conclusion based on the fact that userName is not displayed anywhere in the template

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question