Home > Software engineering >  check if property exist inside List of objects
check if property exist inside List of objects

Time:12-21

I have list of objects response.tasks: {userLastName: ', srCreationDate: '', idNumber: '', firstName: ', insStartDate: null, …} and I want to know if I have some properties for userLastName it will be true for 'example' will be false. I need to write this condition via html

I tried 'userLastName' in response.tasks

response.tasks.hasOwnProperty('userLastName')

response.tasks.includes('userLastName')`

but all of them were false

CodePudding user response:

You have an array (multiple items) so you need to check if "some" item has the property

response.tasks.some(task => task.hasOwnProperty('userLastName'))

or "every" item has the property

response.tasks.every(task => task.hasOwnProperty('userLastName'))

depending on your requirements

CodePudding user response:

You can use in operator.

The in operator returns true if the specified property is in the specified object or its prototype chain.

Example:

interface I1 {
    userLastName: string
}


let myVar: I1 = {
    userLastName: 'test'
}

console.log('userLastName' in myVar); // returns true
  • Related