Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate Property through object?

How do I validate the property through object? I have define the list of Property in the checkProperty

I expected missingFields to return Batch.Name is missing.

Currently is is outputting [ 'Batch.Id', 'Batch.Name' ] which is wrong.

let data = {
    Batch: {
        Id: 123,
    },
    Total: 100,
}

let checkProperty = ['Total', 'Batch.Id', 'Batch.Name'];

let missingFields = [];
checkProperty.forEach(field => {
    if (!data[field]) {
        missingFields.push(field);
    }
});

console.log(missingFields);
like image 432
I'll-Be-Back Avatar asked Dec 07 '25 06:12

I'll-Be-Back


2 Answers

You'll have to use something like reduce after splitting on dots to check whether the nested value exists:

let data = {
  Batch: {
    Id: 123,
  },
  Total: 100,
}

let checkProperty = ['Total', 'Batch.Id', 'Batch.Name'];

let missingFields = [];
checkProperty.forEach(field => {
  const val = field.split('.').reduce((a, prop) => !a ? null : a[prop], data);
  if (!val) {
    missingFields.push(field);
  }
});

console.log(missingFields);
like image 142
CertainPerformance Avatar answered Dec 09 '25 19:12

CertainPerformance


You can use this

The reason why thisdata[field]when dodata[Batch.Id]it tries to check at the first level key of object. in our case we don't have any key such asBatch.Id.

For our case we need `data[Batch][Id]` something like this which first searches 
 for `Batch` property and than or the found value it searches for `Id`.

let data = {
    Batch: {
        Id: 123,
    },
    Total: 100,
}

let checkProperty = ['Total', 'Batch.Id', 'Batch.Name'];

let missingFields = [];
checkProperty.forEach(field => {
    let temp = field.split('.').reduce((o,e)=> {
     return o[e] || data[e]
    },{});

    if (!temp) {
        missingFields.push(field);
    }
});

console.log(missingFields);
like image 43
Code Maniac Avatar answered Dec 09 '25 18:12

Code Maniac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!