Javascript: data validation on array of objects

Viewed 116

I am running this task to teach my brother, he is asked to create a Javascript simple program to validate this data

[
    {code: ‘10001’, amount: ‘’},
    {code: ‘10002’, amount: ’50.00’},
    {code: ‘’, amount: ’60.00’},
    
]

I need to show the errors that if there is an amount, code shouldn't be empty.

3 Answers

You can use .some:

const data = [
  {code: '1000', amount: ''},
  {code: '10002', amount: '50.00'},
  {code: '', amount: '60.00'},   
];

const isInValid = data.some(e => e.amount && !e.code);

console.log("Data is not valid?", isInValid);

Or use .every:

const data = [
  {code: '1000', amount: ''},
  {code: '10002', amount: '50.00'},
  {code: '', amount: '60.00'},   
];

const isValid = data.every(e => !e.amount || e.code);

console.log("Data is valid?", isValid);

Credit to @Majed Badawi, but with fixed validation expression.

const data = [
  {code: '1000', amount: ''},       // is okay
  {code: '10002', amount: '50.00'}, // absolutely valid
  {code: '', amount: '60.00'},      // invalid
  {code: '', amount: ''},           // empty but still valid
];

const validFlags = data.map(e => !e.amount || e.code);
const isValid = validFlags.every(f => f);

console.log("Validation per record", validFlags.map(Boolean));
console.log("Final result", isValid);

I mean if you is always getting an array of objs why not use Joi You can define yow schemas and set the characteristics or needs of each prop on them objs https://joi.dev/api/?v=17.3.0

Related