0

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 :)

1
  • console.log(Object.keys(body).every(key => Array.isArray(body[key]))); should do the trick. Commented May 9, 2019 at 9:13

2 Answers 2

2

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
}

Sign up to request clarification or add additional context in comments.

Comments

2

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 = "[email protected]"
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 = "[email protected]"
const body = { foo: 'bar' }
console.log(Object.keys(body) instanceof Array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.