2

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
D.Mark
  • 537
  • 1
  • 11
  • 23
  • 1
    you will have to build your own function that compares them manually by iterating through the object keys. AFAIK, there is no way to do what you want that's built in typescript – Abderrahmane TAHRI JOUTI Dec 27 '17 at 09:39
  • Have you tried using if(JSON.stringify(data) === JSON.stringify(dataFromServer) )? – Tomer Dec 27 '17 at 09:48

2 Answers2

2

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.

Logar
  • 1,248
  • 9
  • 17
Hai Alaluf
  • 757
  • 7
  • 15
0

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

orangespark
  • 631
  • 6
  • 19