watsbeat
watsbeat

Reputation: 151

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

Upvotes: 0

Views: 1416

Answers (2)

briosheje
briosheje

Reputation: 7446

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
}

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370729

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

Upvotes: 2

Related Questions