如何检查vue.js中的数组是否已经存在?

时间:2017-01-04 00:00:15

标签: javascript vuejs2 vue.js

我有这个数组,我在点击时添加值,但我想检查值是否已经在数组中,如果它什么都不做。我尝试使用indexOf,但每次都得到相同的结果

this.fields.push(this.field);
      this.field = { value: '' };

3 个答案:

答案 0 :(得分:2)

您是否确定value属性是否在数组中?如果是这样,您可以使用Array.some()

var exists = this.fields.some(function(field) {
  return field.value === this.field.value
});

if (!exists) {
  this.fields.push(this.field);
}

答案 1 :(得分:1)

在对象数组中,最好使用Array.some()

this.users = [{id : 1, name : 'Jonh Doe'},{id : 2, name : 'Mary Jean'}]

if(!this.users.some(data => data.id === 1)){
    //exists because Jonh Doe has id 1
}else{
   //don't exists
}

来源:https://www.samanthaming.com/

答案 2 :(得分:0)

这可能是详细且简单的解决方案。

在JavaScript或Jquery中

//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
{
   // value exists in array
   //write some codes
}

// array with objects
var arr = [
      {x:'a', y:'b'},
      {x:'p', y:'q'}
  ];

// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// or y:'q' exists in arr
var check = arr.filter(function (elm){
    if (elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p' && elm.y == 'q')
    {
       return elm; // returns length = 1 (object exists in array)
    }
});

// in all cases
console.log(check.length); // returns 1

if (check.length > 0)
{
   // returns true
   // object exists in array
   //write some codes
}

在Vue中

<script>
    export default {
        data: function () {
            return {
               arr = [
                   {x:'a', y:'b'},
                   {x:'p', y:'q'}
                ],
             }
         },
        methods: {

            // assign this function to any event of any dom
            checkObjInArr = function(){

                     var check = this.arr.filter(function (elm) {
                         if (elm.x == 'a' && elm.y == 'M') {
                                 return elm;
                            }
                      });
                     console.log(check.length > 0); // returns 1
                     if (check.length > 0)
                        {
                            // returns true
                            // object exists in array
                            //write some codes
                         }
                },                
        },
     }
</script>