简体   繁体   中英

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 = "john@gmail.com"
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 :)

One option is to check the Object.values of the body , and see if .every one of them is an array with nonzero length:

 const email = "john@gmail.com" const body = { "fruit": ["apple"], "vegetables": ["carrot", "beans"] } const ok = email && Object.values(body).every(val => Array.isArray(val) && val.length !== 0); if (ok) { console.log('ok'); } else { // handle error } 

The problem with

Object.keys(body) instanceof Array

is that this will always return true if body is an object:

 const email = "john@gmail.com" const body = { foo: 'bar' } console.log(Object.keys(body) instanceof Array); 

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 = "john@gmail.com" 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 } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM