admin管理员组

文章数量:1355582

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?

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

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?

var array=[{"id":100,"output":false},{"id":100,"output":false},
{"id":100,"output":true}]    
Share Improve this question asked Oct 11, 2016 at 11:43 Ali-AlrabiAli-Alrabi 1,7106 gold badges30 silver badges61 bronze badges 4
  • use a for-loop :) – Ric Commented Oct 11, 2016 at 11:45
  • Could you show the code and which is your issue with it? – Mario Santini Commented Oct 11, 2016 at 11:45
  • Possible duplicate of How to loop through an array containing objects and access their properties – Turnip Commented Oct 11, 2016 at 11:45
  • use Array.prototype.some should stop the iteration once one value is found and return a Boolean – Endless Commented Oct 11, 2016 at 11:45
Add a ment  | 

4 Answers 4

Reset to default 11

You could use Array#some

The some() method tests whether some element in the array passes the test implemented by the provided function.

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 patible

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)

本文标签: Check javascript array of objects propertyStack Overflow