endtoend6 endtoend6 -4 years ago 81
Javascript Question

Validating arrays in an object of arrays in Javascript

I have a query object that looks like this

{
"regions": [],
"countries": [],
"channels": [],
"partners": [],
"branches": [],
"agents": []


}

After populating the arrays in the object it looks like this.

{
"regions": [{
"key": "101",
"value": "Middle East(XX)"
}],
"countries": [],
"channels": [],
"partners": [{
"key": "201",
"value": "Partner A"
}, {
"key": "202",
"value": "Partner B"
}],
"branches": [{
"key": "401",
"value": "Bangalore"
}, {
"key": "402",
"value": "Chennai"
}],
"agents": [{
"key": "501",
"value": "IBM - Metlife"
}]
}


I'm trying to loop through each of these arrays and determine if I should show the filter component. If any of the arrays in the object holds value, I should be showing the filter component

The code:

case false:
let itemsInQuery = 0;
Object.keys(query).forEach((item) => {
itemsInQuery = query[item].length ? itemsInQuery++ : itemsInQuery;
})
itemsInQuery ? this.setState({showBubbles: true, query}) : this.setState({showBubbles: false, query})
break;


I'm not sure what is wrong here, but
itemsInQuery
is always zero. Also, is there a better way to do this?

Thank you in advance!

Answer Source

If any of the array have items in, you want a boolean to be true?

This sounds like a case for .some which on an array will take a predicate and return true if any item in that array matches the predicate.

const shouldShow = Object.keys(data).some(key => data[key].length > 0)

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download