4

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}]    
Ali-Alrabi
  • 1,515
  • 6
  • 27
  • 60
  • use a for-loop :) – Ric Oct 11 '16 at 11:45
  • Could you show the code and which is your issue with it? – Mario Santini Oct 11 '16 at 11:45
  • Possible duplicate of [How to loop through an array containing objects and access their properties](http://stackoverflow.com/questions/16626735/how-to-loop-through-an-array-containing-objects-and-access-their-properties) – Turnip Oct 11 '16 at 11:45
  • use [Array.prototype.some](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some) should stop the iteration once one value is found and return a Boolean – Endless Oct 11 '16 at 11:45

4 Answers4

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1
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
Robiseb
  • 1,576
  • 2
  • 14
  • 17
0

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

spitterfly
  • 28
  • 1
  • 4
0

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)
Endless
  • 34,080
  • 13
  • 108
  • 131