fauverism
fauverism

Reputation: 1992

Return if a falsy value is in an array

What I want to happen is if any value is falsy, return just the error and never return the hooray. I'm using lodash.

var jawn = [
    {
        "cheese"  : true,
        "with"    : true,
        "without" : true
    },
    {
        "cheese"  : true,
        "with"    : true,
        "without" : true
    },
    {
        "cheese"  : true,
        "with"    : false,
        "without" : true
    },
    {
        "cheese"  : true,
        "with"    : true,
        "without" : true
    }      
];

_.forEach(jawn, function (item) {
    if(item.with === false) {
        console.log('error');
    } else {
        console.log('hooray');
    }
});

Upvotes: 0

Views: 76

Answers (2)

tokland
tokland

Reputation: 67850

Since your are using undescore, check Collections.every/all:

const msg = _(jawn).all(obj => obj.with) ? "hooray" : "error";
console.log(msg);

Upvotes: 3

codejockie
codejockie

Reputation: 10854

var jawn = [{
    "cheese": true,
    "with": true,
    "without": true
  }, {
    "cheese": true,
    "with": true,
    "without": true
  }, {
    "cheese": true,
    "with": false,
    "without": true
  },
  {
    "cheese": true,
    "with": true,
    "without": true
  }
];

const msg = jawn.some(item => !item.with) ? "error" : "hooray";
console.log(msg);

Upvotes: 3

Related Questions