检查对象数组

时间:2016-07-08 15:41:01

标签: javascript

我有这个数组:

var data= [{IsNormal:"true", Name:"Mike"},
         {IsNormal:"true", Name:"Tom"},
         {IsNormal:"false", Name:"Clause"},
         {IsNormal:"true", Name:"Timm"},
         {IsNormal:"true", Name:"Marta"},
         {IsNormal:"true", Name:"Dora"}];

我需要编写函数来检查数组中的至少一个对象是否具有属性IsNormal等于false,如果有函数必须返回false,否则它必须返回true。

这是我的实施:

    function chekStatus(data) {
        _.each(inspections, function (value, key) {
            if (!value.IsNormal)
                return false;
            return true;
        });
    }

但是我想用数组原型javascript功能写一些更优雅的东西。

2 个答案:

答案 0 :(得分:3)

使用Array.some

 function chekStatus(data) {
     return data.some(function (item) { return !item.IsNormal; })
 }

注意,IsNormal值应为boolean,而不是string

var data= [{IsNormal:true, Name:"Mike"},
     {IsNormal: true, Name:"Tom"},
     {IsNormal: false, Name:"Clause"},
     {IsNormal: true, Name:"Timm"},
     {IsNormal: true, Name:"Marta"},
     {IsNormal: true, Name:"Dora"}];

Working fiddle

答案 1 :(得分:1)

您可以使用Array.some()

data.some(obj => !obj.IsNormal)