Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Validate an expected object structure in JavaScript

I need to have an expected format for the response object in my script as:

  let expectedObjectFormat = {
    data: 'someValue',
    errors: 'someValue',
    abort: 'someValue',
    retryData: 'someValue'
  }

I need to have a validation script that would check if the runTimeObject has fields in the expected format or not.

  1. If there’s any field missing it should be reported.
  2. If there are any extra fields that should be reported.
let runtimeObjectFormat = {
    data: 'someDifferentValue',
    errors: 'someDifferentValue',
    abort: 'someDifferentValue',
  }

This should give ‘retryData’ field missing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let runtimeObjectFormat = {
    data: 'someDifferentValue',
    errors: 'someDifferentValue',
    abort: 'someDifferentValue',
    retryData: 'someDifferentValue',
    extraField: 'someDifferentValue
  }

This should give ‘extraField’ field is unexpected

Can someone provide Javascript code for same?

>Solution :

I have wrote a function for this use case

function checkObjectFormat(runtimeObj, expectedObj){
    let runtimeKeys = Object.keys(runtimeObj);
    let expKeys = Object.keys(expectedObj);

    let extraFields = runtimeKeys.filter(x => !expKeys.includes(x));
    let missingFields = expKeys.filter(x => !runtimeKeys.includes(x));

    return {
        extraFields,
        missingFields
    }
}

Usage:

checkObjectFormat(runtimeObjectFormat, expectedObjectFormat)

It will return a object that contains array of extra and missing fields

Output for a object with extra key:

{
    "extraFields": [
        "extraField"
    ],
    "missingFields": []
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading