Kyle
Kyle

Reputation: 1183

Check if any key values are false in an object

Question:

I'm looking for a simple solution to check if any key values are false in an object.

I have an object with several unique keys, however, they only contain boolean values (true or false)

var ob = {  stack: true, 
            overflow: true, 
            website: true 
         };

I know that I can get the number of keys in an Object, with the following line:

Object.keys(ob).length // returns 3

Is there a built in method to check if any key value is false without having to loop through each key in the object?


Solution:

To check if any keys - use Array.prototype.some().

// to check any keys are false
Object.keys(ob).some(k => !ob[k]); // returns false

To check if all keys - use Array.prototype.every().

// to check if all keys are false 
Object.keys(ob).every(k => !ob[k]); // returns false 

Upvotes: 25

Views: 22666

Answers (5)

Md Ali
Md Ali

Reputation: 1

You can use key-validator library here. Its having all essential features to verify object.

Installation

  npm i key-validator

Import


  import Validator from "key-validator"

  let V = Validator(...);

Working

Validator function works in 2 steps:-

  1. First it digs all sub keys and verifies weather it is null or "".
  2. Validating as per user inputs.

Usage

let colors = {
      redish: ["crimson", "orange"],
      greenish: ["yellow", "limegreen", ""],
      blackish: "",
      }

console.log(Validator({
    data: colors
})

OUTPUT Will be:-

{
    stat: false
    errors: [
        0: "greenish['2']"
        1: "blackish"
    ]
    msg: {
    }
}

Explanation:-

  1. stat = true | false, Returns validation status.
  2. errors = [], Having path of keys that is undefined || null || "" || key.length == 0
  3. msg = [], Will show messages defined by user on caught error in particular keys.

Full-Fledged features example:

Here we have a Object Details:-

let Details = {
  name: {
    firstName: "John",
    middleName: "",
    lastName: "Doe",
  },
  age: 22,
  location: {
    country: "India",
    city: "New Delhi",
    streets: "Lorem porem impson",
  },
  sibilings: [],
};




TEST 1

  Validator({
    data: Details,
    ignore: ["name.middleName"],
    rules: {
      age: (value) => {
        return [value > 28, "AGE NOT VALID "];
      },
    },
  });

OUTPUT WILL BE:-


{
    stat: false
    errors: {
        0: age
        1: sibilings
    }
    msg: {
        0: AGE NOT VALID
    }
}


TEST 2

  Validator({
    data: Details,
    ignore: ["name.middleName", "sibilings"],
    rules: {
      age: (value) => {
        return [value > 28, "AGE NOT VALID "];
      },
    },
  });

OUTPUT WILL BE:-


{
    stat: false
    errors: {
        0: age
    }
    msg: {
        0: AGE NOT VALID
    }
}


METHODS :-

  1. data => Main object that to be validated.
  2. ignore = [...] => Specify key that to be ignored.
  3. required = [...] => Only specifed key will be validated and remaining will be ignored.
  4. rules = {keyname: (value)=>[STAT, ERROR_MESSAGE]} => Each keys will be validated with function and must return [STAT, ERROR_MESSAGE] to validate.

Upvotes: 0

Pearl
Pearl

Reputation: 21

To check if all values are false

Object.values(ob).every(v => !v); 

enter image description here

Upvotes: 0

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

You can create an arrow function isAnyKeyValueFalse, to reuse it in your application, using Object.keys() and Array.prototype.find().

Code:

const ob = {
  stack: true,
  overflow: true,
  website: true
};
const isAnyKeyValueFalse = o => !!Object.keys(o).find(k => !o[k]);

console.log(isAnyKeyValueFalse(ob));

Upvotes: 1

Manoj Shrestha
Manoj Shrestha

Reputation: 4684

Here's how I would do that:

Object.values(ob).includes(false);      // ECMAScript 7

// OR

Object.values(ob).indexOf(false) >= 0;  // Before ECMAScript 7

Upvotes: 13

tymeJV
tymeJV

Reputation: 104775

You can use the Array.some method:

var hasFalseKeys = Object.keys(ob).some(k => !ob[k]);

Upvotes: 32

Related Questions