简体   繁体   English

angularjs:检查id是否存在于数组中?

[英]angularjs: check for an id exists in an array r not

 var vm = this; vm.usableDeposits = []; for (var i = 0; i < billableChargeCodes.length; i++) { var deposits = usableDeposits.filter(function(ud) { return ud.billinggroupuid == billableChargeCodes[i].billinggroupuid || ud.billinggroupuid == billableChargeCodes[i].billingsubgroupuid || ud.departmentuid == billableChargeCodes[i].departmentuid || !ud.entypeuid || ud.entypeuid == entypeuid }) for (var i = 0; i < deposits.length; i++) { var depositid = deposits[i]._id; 

first time, vm.usableDeposits[] is empty. 第一次, vm.usableDeposits[]为空。 I have to check deposits[i]._id exists in vm.usableDeposits[] or not. 我必须检查deposits[i]._id存在于vm.usableDeposits[] How to check vm.usableDeposits[] empty array _id with deposits[i]._id ? 如何使用deposits[i]._id检查vm.usableDeposits[]空数组_id? if id not exists in vm.usableDeposits[] , then i want to push the element into vm.usableDeposits[] 如果id在vm.usableDeposits[]不存在,那么我想将元素推入vm.usableDeposits[]

You can simply use the indexOf operator in JavaScript to check if a value exists in the array or not. 您只需在JavaScript中使用indexOf运算符即可检查数组中是否存在值。 It returns -1 if the value is not in the array, else, it returns the index of the element in the array . 如果值不在数组中,则返回-1 ;否则,返回array元素的索引。

The syntax goes like this - 语法如下:

if(myArray.indexOf(value) !== -1) {
    // do this
} else {
    // do that
}

Hope this helps. 希望这可以帮助。

You can use .some 您可以使用.some

deposits.some(o=> vm.usableDeposits.indexOf(o.id))

to check if the ID in deposits array is in vm.usableDeposits . 检查deposits数组中的ID是否在vm.usableDeposits .some will return true if condition is true and false otherwise .some将返回true ,如果条件为真,否则为假

$scope.findIndexInData = function(data, property, value) {
    var result = -1;
        if((!!data) && (!!property) && (!!value)){
            data.some(function (item, i) {
                if (item[property] === value) {
                    result = i;
                    return true;
                }
            });
        }
    return result;
  }

Pass on the array as the First Element. 将数组作为第一个元素传递。 Property as second element and value you are looking in that array. 属性是您在该数组中查找的第二个元素和值。

Example: 例:

array = [{id:"1234",name:"abc"}, {id:"4567",name"xyz"}] 

So you need to call: 因此,您需要致电:

index = $scope.findIndexInData(array , 'id' , 4567)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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