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}]    
4

4 Answers 4

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);

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

you filter all array objects even if true in first. better use some()
@Maxx I agree :)
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

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.