Edan Ben Ivri
Edan Ben Ivri

Reputation: 25

Express Validate check Object has nested keys

My express server handle a post request which receives a body containing the next JSON object:

"QnsAns": {

    }

How can I validate that object QnsAns HAS nested object? It should look like:

"QnsAns": {
        "Q1": "A1",
        "Q2": "A2",
        "Q3": "A3",
        "Q4": "A4",
        "Q5": "A5"
    }

Using express validator, I tried using '*' wildcard, optional(), exist() but all result with no success

Thanks!

Upvotes: 0

Views: 1100

Answers (2)

Ankit Kumar Singh
Ankit Kumar Singh

Reputation: 557

The question is not very clear. Is this object in JSON format? Can you please post some more details to it so that it will help.

Now, as a simple solution you can do something like this, assuming the object is stored in a variable data.

function checkIfNestedObjectIsEmpty() {

let data = <Your Object>

return (Object.entries(data[Object.keys(data)]).length === 0)
}

Upvotes: 0

Mohit Kumar
Mohit Kumar

Reputation: 359

To check if "QnsAns" constains "Q1" you can use hasOwnProperty

console.log(QnsAns.hasOwnProperty('Q1'));

To check type of Q1, you can use typeOf

console.log(typeof(Q1);

If you have to use this multiple times, try out Joi Validations

Upvotes: 1

Related Questions