简体   繁体   中英

How to compare object (json) with Model(javascript class)

I'm using angular 2 at the moment. And I have array of some data

data: MyModel[] = [
{
  id: 1,
  name: 'Name',
  secondName: 'SecondName'
}

Also MyModel is interface:

interface MyModel {
id: number,
name: string,
secondName: string

Let's imagine, that I received data from Back-End(object json):

{
id: 2,
FIRSTname: 'FName',
secondName: 'SecondName'
}

How can I validate, that keys in object are equals to my interface?

For example field "FIRSTname" is incorrect, then I should throw exception or something else.

Maybe there is a better way in typescript, in es6 you can do:

 const data = [ { id: 2, name: 'FName', secondName: 'SecondName' }, { name: 'foo', secondName: 'bar' }, ]; const validate = ({id, name, secondName}) => id && name && secondName const validData = data.filter(validate) console.log(validData);

Be a ware that if one of the values: id, name, secondName, is null validate will return false.

What if I say that you can define a variable obj implementing the model interface and initialise all its property and then compare the keys of obj with the backend data lets name it respDataObj

Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { //To test values in nested arrays
            if (!this[i].compare(testArr[i])) return false;
        }
        else if (this[i] !== testArr[i]) return false;
    }
    return true;
}
Object.keys(respDataObj).compare(Object.keys(obj))

Compare function courtesy: https://stackoverflow.com/a/6229258/2791802

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM