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

3

我有一个数组,当我点击时向其中添加值,但我想检查该值是否已经存在于数组中,如果存在则不进行任何操作。我尝试使用indexOf方法,但每次都得到相同的结果。

this.fields.push(this.field);
      this.field = { value: '' };
3个回答

7

当处理对象数组时,最好使用Array.some()方法。

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

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

Source: https://www.samanthaming.com/


1
帮了我很多忙,但我发现你在if语句中有一个小错误,因此它会说“如果不”,所以如果在你的情况下“id”存在,它将跳到else而不是if。但我已经使用了你的解决方案,谢谢 :) - Hashaam Ahmed
1
你说得对,我已经纠正了。这是因为在我的示例中,当一个元素没有在数组中找到时,我想执行一个操作。☺ - Vladimir Salguero

5
你是通过value属性来确定它是否在数组中吗?如果是,你可以使用Array.some()
var exists = this.fields.some(function(field) {
  return field.value === this.field.value
});

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

1
这可能是一个详细且易懂的解决方案。
在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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接