if field exists do something in javascript

You can use the in operator to check if an object has a certain property. For example:

index.tsx
if ('fieldName' in myObject) {
  // do something if the field exists
} else {
  // do something else if the field doesn't exist
}
130 chars
6 lines

Alternatively, you can also use the hasOwnProperty method to check if an object has a property that belongs to itself rather than its prototype chain. For example:

index.tsx
if (myObject.hasOwnProperty('fieldName')) {
  // do something if the field exists
} else {
  // do something else if the field doesn't exist
}
143 chars
6 lines

Remember to replace fieldName with the actual name of the field you want to check, and myObject with the name of the object you want to check the field on.

related categories

gistlibby LogSnag