Errorhandling arrays within obj

objName is an object that contains properties, some of which are arrays.
I’m trying to check that the properties and elements of the obj are not undefined, null or have empty string.

function fieldChecker(obj) {
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      const value = obj[key];

      // Check if the value is an array
      if (Array.isArray(value)) {
        const hasInvalidElement = value.some(function(element) {
          return element === undefined || element === null || element === '';
        });

        if (hasInvalidElement || key === undefined || key === null || key === '') {
          console.log('-', key, ' or its elements are missing or empty. Key Value: ', key, ' Array Value:   ', value);
        }
      } else {
        // For non-array values, perform the regular check
        if (key === undefined || key === null || key === '' || value === undefined || value === null || value === '') {
          console.log('-', key, ' is missing or empty. Key Value: ', key, ' Value: ', value);
        }
      }
    }
  }
}
fieldChecker(objName);

I have intentionally altered an array so I can see that the value is an empty sting but this code is not picking it up. I’m fairly new to JS so am not sure I completely understand how to target the elements for error handling.

  • hasInvalidElement is local to the first if block. You need to move the declaration to function scope.

    – 

  • let and const are block-scoped, var is function-scoped.

    – 

  • key can never be undefined or null. Object keys are always strings.

    – 

  • Thanks so much for your comments Barmar, this has tidied up my code however my original issue is still unresolved. in this case the objectName has an array within. I have removed the value of one of the elements of the array but this code is running through without picking up this error. I’mm not sure how i’m supposed to target the specific elements within the key

    – 

  • Please add the object to the code snippet so we can test it.

    – 

A simple recursion would do the trick:

function fieldChecker(obj, path="") {
  
  if(obj === null || obj === undefined || obj === '') {
    console.log(path, 'is empty');
    return;
  }

  if(Array.isArray(obj)){
    for(let i = 0; i < obj.length; i++){
       fieldChecker(obj[i], `${path}[${i}]`);
    }
  } else if (obj.__proto__ === Object.prototype){
    for(const k in obj){
      fieldChecker(obj[k], `${path}${path ? '.' : ''}${k}`);
    }
  }
}
fieldChecker(objName);
<script>
const objName = {
  arr: [0, 1, 2, {foo:undefined}, undefined],
  test: null,
  foo: 'foo',
  baz: { list: [0, 1, null, {bad: undefined}], notList: false},
  obj:{
    bar: 'bar',
    another:''
  }
};
</script>

Leave a Comment