简体   繁体   English

检查javascript数组对象属性

[英]Check javascript array of objects property

I have the following javascript array of objects ,I need to check output property if at least one object is true return true else return false,Can anyone help me to implement that? 我有以下javascript对象数组,如果至少有一个对象为true,我需要检查输出属性返回true否则返回false,有人可以帮我实现吗?

var array=[{"id":100,"output":false},{"id":100,"output":false},
{"id":100,"output":true}]    

You could use Array#some 你可以使用Array#some

The some() method tests whether some element in the array passes the test implemented by the provided function. some()方法测试数组中的某个元素是否通过了由提供的函数实现的测试。

 var array = [{ "id": 100, "output": false }, { "id": 100, "output": false }, { "id": 100, "output": true }]; result = array.some(function (a) { return a.output; }); console.log(result); 

function hasOneTrue(a){
  return !!a.filter(function(v){
    return v.output;
  }).length;
}

var array = [{"id":100,"output":false}, {"id":100,"output":false}, {"id":100,"output":true}]
console.log(hasOneTrue(array)); // true

You could Loop over the array and check every property. 你可以遍历数组并检查每个属性。

var array = [
    {"id":100,"output":false},
    {"id":100,"output":false},
    {"id":100,"output":true}
];

function testOutput ( array ) {
    for (el in array)
        if ( el.output ) return true;

    return false;
}

testOutput (array);

Best Regards 最好的祝福

fastest + most compatible 最快+最兼容

 var result = false var json = [{"id":100,"output":false},{"id":100,"output":false},{"id":100,"output":true}] for( var i = json.length; !result && i; result = json[--i].output ); console.log("at least one? ", result) 

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

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