简体   繁体   中英

javascript (angularjs) check if value exists in js object

I have the following object

{
  0 : false,
  1 : true,
  2 : false
}

What i need to do is i loop through these and set some of them to true or false depending on the condition but i need a function to check if all values are set to true or if false exists in the object.

I have the following to check if the value is false to do something

 angular.forEach($scope.keyFiles, function (val, key) {
        if(val == false) {
              $scope.loadCanvas(key);
              return key;
        }
 });

but i need something now to check if false exists at all in any of the values and if all values are set to true.

Im new to javascript so excuse me if this sounds like a simple solution.

Hope this is what you are looking for.

function containsFalse(obj){
    for(var prop in obj){
       if(obj[prop] === false) return true;
    }
    return false;
}

Here is a plain javascript way of doing it:

var keyFiles = {
  0 : false,
  1 : true,
  2 : false
};

var falseExists = false;
for (var prop in keyFiles) {
    if (keyFiles.hasOwnProperty(prop) && keyFiles[prop] === false) {
        falseExists = true;
        break;
    }
}

console.log(falseExists);

More on hasOwnProperty in this MDN link

In modern browsers (ie, IE 9+, Chrome 5+ etc) the code can be simplified as below:

for (var prop in Object.getOwnPropertyNames(keyFiles)) {
    if (keyFiles[prop] === false) {
        falseExists = true;
        break;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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