Search code examples
javascriptarraysjavascript-objects

How to check if Javascript object value is array and not empty


Before I run some code, I need to check whether the data I'm passing (from a JSON file) is correct.

Specifically, I'm trying to check if the email exists and my body object: - has at least one key - each key has a value - and the value must be an array with at least one item populating it.

const email = "[email protected]"
const body = {
   "fruit": ["apple"],
   "vegetables": ["carrot", "beans"]
}

Here's what I've tried so far:

if (email && Object.keys(body).length > 0 && Object.keys(body) instanceof Array) {
   // run some code
} else {
  // log error
}

Is instanceof the best method here? I'm wondering if I should use .isArray() instead. Also should I be performing this on Object.keys or Object.value?

Thanks :)


Solution

  • You may want to use Object.keys and check that each value is an array and has at least one value.

    Object.keys(body).every(key => Array.isArray(body[key]) && body[key].length !== 0)
    

    This will check, for each body key, that it's value is an array (using Array.isArray) and that it has at least one element in it (using body[key].length).

    Furtherly, .every returns true only if all the tests passed.

    Array.every MDN documentation

    Object.keys MDN documentation

    const email = "[email protected]"
    const body = {
       "fruit": ["apple"],
       "vegetables": ["carrot", "beans"]
    }
    
    if (email && Object.keys(body).length > 0 && Object.keys(body).every(key => Array.isArray(body[key]) && body[key].length !== 0)) {
       console.log('hooray!');
    } else {
      // log error
    }