How to know if all javascript object values are true?

前端 未结 5 897
再見小時候
再見小時候 2020-12-23 16:21

In JavaScript, I need to know if all object items are set to true.

If I have the following object:

var myObj = {title:true, name:true, email:false};
         


        
5条回答
  •  既然无缘
    2020-12-23 16:49

    In modern browsers:

    var allTrue = Object.keys(myObj).every(function(k){ return myObj[k] });
    

    A shorter alternative to this is:

    var allTrue = myObj.every(function(i) { return i; });
    

    If you really want to check for true rather than just a truthy value:

    var allTrue = Object.keys(myObj).every(function(k){ return myObj[k] === true });
    

提交回复
热议问题