How to dynamically check if a property exists in an object?

Solution for How to dynamically check if a property exists in an object?
is Given Below:

By dynamically I mean that this prop won’t be the same depending where I am checking it from.
For example, I have this hook:

export const useErrorBorder = (fieldName: string) => {
  const { formState: { errors } } = useFormContext()
  const colors = { clean: 'blue.500', error: 'red.500' }

  let showErrorBorder = colors.clean

  if (errors && Object.keys(errors)?.length && fieldName) {
    showErrorBorder = colors.error
  } else {
    showErrorBorder = colors.clean
  }

  if (!fieldName) {
    showErrorBorder="inherit"
  }

  return showErrorBorder
}

Where I need to check if fieldName exists in the errors object of the formState from useFormContext hook.

So when I call this hook, I use like this:

  const handleErrorHook = useErrorBorder(
    Object.keys(errors)?.length ? errors?.logic[conditionIndex]?.skipQuestionsSelect : '',
  )

Or depending if I call it on another component:

  const handleErrorHook = useErrorBorder(
    Object.keys(errors)?.length ? errors?.logic[conditionIndex]?.scenarios[scenarioIndex]?.operator : ''
  )
<Comp focusBorderColor={handleErrorHook?.showErrorBorder || 'inherit'}` />

As you noticed skipQuestionsSelect is not inside the scenarios array. And, when skipQuestionsSelect or operator are empty they will be remove from their positions

So I am getting errors like these:
enter image description here

So what will be the best solution to avoid this error?

You’re not properly optional chaining your errors?.logic[conditionIndex]?.scenarios[scenarioIndex]?.operator bit.

If you want to optional chain with a [key] access, use ?.[key], e.g. errors?.logic?.[conditionIndex]?.scenarios?.[scenarioIndex]?.operator.

In Javascript there are two ways to access object properties, that are dot notation: something.bar or with bracket notation: something['bar']
With the bracket notation you can access the object properties dynamically passing the string value of the key inside the bracket.

So in your case that you have the key stored on a variable so you simply put the variable with the key name inside the brackets like this:

var objectKey = 'someKey';
var objectWithSomeKey = {
  someKey: 'Hello'
};

console.log(objectWithSomeKey[objectKey]);