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 :)
console.log(Object.keys(body).every(key => Array.isArray(body[key])));should do the trick.