Flatten errors

by nicotr014

JavaScript

const flattenErrors = (errors) => {
    // Return errors if it's an array
    if(Array.isArray(errors))
      return errors
    
    // Return array
    if(typeof errors === 'string')
      return [errors]

    let flatErrors = []

    for(let prop in errors) {
      const value = errors[prop]
      
      // Value is the error
      if(typeof value === 'string')
				flatErrors.push(value)
      // Value is an array
      else if(Array.isArray(value)) {
        // Process each index
        for(let i in value)
          flatErrors = flatErrors.concat(flattenErrors(value[i]))
      }
      // Value is an object
      else if(typeof value === 'object')
        flatErrors = flatErrors.concat(flattenErrors(value))
    }

    return flatErrors
 }
  
 const errors = {
 	primary_recording: ['primary_recording error'],
  sw_percentage: 'sw_percentage error',
 	song_writers: {
  	_meta: [],
    errors: [
    	{
      	_meta: [],
        percent: ['percent error'],
        publishers: {
        	errors: [],
          meta: ['some publisher meta error'],
        },
        role_code: ['role_code error'],
        writer: {
        	_meta: [],
          formal_name: [],
          ipi: ['ipi error'],
          pro: ['pro error'],
        }
      }
    ]
  }
}

console.log(flattenErrors(errors))