Ajv: how to make a property nullable conditionally depending on other property

Viewed 84

I have an object that can be in one of 4 states:

  1. {"A": "something", "B": [{"C": "D"}]}
  2. {"A": "", "B": [{"C": "D"}]}
  3. {"A": "something", "B": null}
  4. {"A": "", "B": null}

In my Ajv schema validation I want to make the property "B" nullable: true only if the property "A" is not an empty string.

How can I achieve this?

1 Answers

I hope the below helpers function helps you. You can make changes in assignment value as you need

function mappNullable(obj, nonNullable, nullableProperty) { 
   if(obj[nonNullable] != '') { 
      obj[nullableProperty] = {nullable: true};
   }
   return;
}
const t1 = {"A": "something", "B": [{"C": "D"}]};
const t2 = {"A": "", "B": [{"C": "D"}]};
const t3 = {"A": "something", "B": null};
const t4 = {"A": "", "B": null};
mappNullable(t1, "A", "B");
mappNullable(t2, "A", "B");
mappNullable(t3, "A", "B");
mappNullable(t4, "A", "B");
console.log(t1);  // {"A": "something", "B": {nullable: true}};
console.log(t2); // {"A": "", "B": [{"C": "D"}]};
console.log(t3); // {"A": "something", "B": {nullable: true}};
console.log(t4); //  {"A": "", "B": null};

Related