展平以从对象中提取错误

时间:2019-01-27 22:48:35

标签: lodash

如何将这样的列表转换为错误消息的扁平数组:

 "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"
    ]
  },

尝试var arr = _.toArray(data.errors);,但是它不会使数组中具有多个项目的对象变平。

1 个答案:

答案 0 :(得分:2)

Lodash

使用_.values()(或_.toArray())获取错误消息数组,并使用_.flatten()转换为单个数组。

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>

香草JS

使用Object.values()获取错误消息数组,并使用Array.flat()转换为单个数组

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)