检查所有属性是否都为false

时间:2016-09-19 07:41:26

标签: javascript reactjs

反应状态如下:

[
   {type: "Benzine", active: false},
   {type: "Diesel", active: false},
   {type: "Electricity", active: false}
]

如何检查所有active值是否为false。

有没有办法用lodash做到这一点?

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容测试每个active属性是否为真:



    var arr = [
       {type: "Benzine", active: false},
       {type: "Diesel", active: false}, 
       {type: "Electricity", active: false}
    ]

    console.log(arr.every(obj => obj.active));






var arr = [
       {type: "Benzine", active: true},
       {type: "Diesel", active: true}, 
       {type: "Electricity", active: true}
   ]

   console.log(arr.every(obj => obj.active));






    var arr = [
       {type: "Benzine", active: false},
       {type: "Diesel", active: true}, 
       {type: "Electricity", active: false}
    ]

    console.log(arr.every(obj => obj.active));




答案 1 :(得分:1)

您可以使用loadash的每个函数来检查每个对象的active是否为false。

var data = [
    {type: "Benzine", active: false},
    {type: "Diesel", active: false},
    {type: "Electricity", active: true}
];
// First argument is the data and second argument is the predicate to check
var res = _.every(data, {active: false}); // Returns true if all elements pass the predicate match else false.
document.getElementById("data").innerHTML  =  res;