Last active
July 20, 2017 12:27
-
-
Save dobromir-hristov/e02302784d477867215416cb149e5eed to your computer and use it in GitHub Desktop.
Transform Objects and Arrays to String with breaks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Transform an array of messages from laravel error message bag to be a single html string with breaks | |
* @param {Object | Array | String} message | |
* @example | |
* message = { username: ['some error', 'maybe another error'], email: ['another error', 'and another error']} | |
* message = { username: 'some error', email: 'and another error'} | |
* message = ['some error', 'and another error'] | |
* message = [['some error'], ['and another error']] | |
* message = 'some error' | |
* @return { String } | |
*/ | |
export default function transformMessage (message) { | |
let newMessage = message | |
// Check if messages are an Object of array items | |
if (typeof message === 'object') { | |
newMessage = [] | |
Object.keys(message).forEach((key) => { | |
// We flatten the message if its an obj or just pass it if is a string. | |
if(typeof message[key] === 'object'){ | |
newMessage.push(...message[key]) | |
} else { | |
newMessage.push(message[key]) | |
} | |
}) | |
newMessage = newMessage.join(' <br />') | |
} | |
// its not an object so we just return it. | |
return newMessage | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment