Search code examples
lodash

flatten to extract errors from object


How do I convert a list like this into flattened array of error messages:

 "errors": {
    "Client": [
      "User client does not exist"
    ],
    "Password": [
      "User password has to have more than 6 characters",
      "The password and confirmation password do not match."
    ],
    "ConfirmPassword": [
      "Confirm Password has to have more than 6 characters"
    ]
  },

tried var arr = _.toArray(data.errors); but it doesnt flattent the objects that have multiple items in the array.


Solution

  • Lodash

    Use _.values() (or _.toArray()) to get an array of error message arrays, and _.flatten() to convert to a single array.

    const errors = {"Client":["User client does not exist"],"Password":["User password has to have more than 6 characters","The password and confirmation password do not match."],"ConfirmPassword":["Confirm Password has to have more than 6 characters"]}
    
    const result = _.flatten(_.values(errors))
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

    Vanilla JS

    Use Object.values() to get an array of error message arrays, and Array.flat() to convert to a single array

    const errors = {"Client":["User client does not exist"],"Password":["User password has to have more than 6 characters","The password and confirmation password do not match."],"ConfirmPassword":["Confirm Password has to have more than 6 characters"]}
    
    const result = Object.values(errors).flat()
    
    console.log(result)