'Validate if object is empty from values in an array - Javascript
I have a data for businesses like below:
{
"business": {
"type": [
"LLC",
"Corporation"
],
"LLC": {
"status": "active",
"profits": 1000000,
"period": "yearly"
},
"corporation": {},
"partnership": {}
}
}
How do I validate the "corporation" object, so if the "type" array contains the string "Corporation", the "corporation" object cannot be empty?
I've tried using validate.js to check if it is empty, it works but I can't specifically put the strings inside the type array to validate it.
const validate = require('validate.js');
if (validate.isEmpty(business.LLC)) {
return wrapper.error('fail', 'Object is empty');
}
Thank you very much for the help 🙏🏻
Solution 1:[1]
let object = {
"business": {
"type": [
"LLC",
"Corporation"
],
"LLC": {
"status": "active",
"profits": 1000000,
"period": "yearly"
},
"corporation": {},
"partnership": {}
}
}
Use includes to check the elements inside array,
object.business.type.includes("Corporation")
Solution 2:[2]
I figured it out and didn't realise as well, thank you dinesh for your answer!
So what I need to do is to check the array first and then check the objects below.
if (payload.business.type.includes('Corporation')) {
if (validate.isEmpty(payload.business.corporation)) {
return wrapper.error('fail', 'Object is empty');
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | dinesh oz |
| Solution 2 | Hasimy |
