Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Raido's avatar
Level 2

How to check does value exists in array with Vue?

I have little brain teaser/freezer. I have following structure in Vue ''' data:{ country-name:'', countries: { id:'', country_name:'', }, countries:[], } ''' country_name has binding with v-model text input and should be compared with array to check is the value already entered. I understand that I should use somekind of custom filter in Vue but I have not figured out how. Can anyone provide a solution?

0 likes
6 replies
InaniELHoussain's avatar

just make sure of the variables and array keys

new Vue({
el :'#app',
data:{ 
    country_name: '',
    countries :[]
},
methods : {
    isExist : function(){
      for(var i=0; i < this.countries.length; i++){
        if( this.countries[i].country_name == this.country_name){
          return true
        }
      }
      return false
    }

    }
})
1 like
hxd's avatar

Write a function in methods, like that,

 methods: {
                // 判断字符在数组中
                inArray: function(needle, haystack) {
                    var length = haystack.length;
                    for(var i = 0; i < length; i++) {
                        if(haystack[i] == needle) return true;
                    }
                    return false;
                }

            }
3 likes
bugsysha's avatar
bugsysha
Best Answer
Level 61

If you are using ES2015 then you can

[].includes(something);
18 likes
Artistan's avatar

thanks @bugsysha I thought I would note that you should be able to just do a validator in Vue 2

    new Vue({
        el: '#app',
        data: {
            country_name: {
                type: String,
                required: false,
                validator: function(value) {
                    return this.countries.includes(value);
                }
            },
            countries: {
                type: Array,
                required: true
            }
        }
    });

Please or to participate in this conversation.