Home > Back-end >  Validate an expected object structure in JavaScript
Validate an expected object structure in JavaScript

Time:09-05

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

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?

CodePudding user response:

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": []
}
  • Related