首页 > 解决方案 > 如何在javascript中摆脱数组中的数组

问题描述

const addressZip = person.get('addresses').filter((address) => address.get('legacy_id')).filter((newAddress) => (
  getZIPErrors(newAddress.get('zip'))
))

执行此函数时, [array(0)]如果没有错误,它会以 . 的形式返回我[array(1)]

如果它没有错误[]并且如果它有错误它应该像['invalid']

标签: javascript

解决方案


您可以在 Array 构造函数中实现 concatAll 方法,然后使用它来展平您的结果:

Array.prototype.concatAll = function() {
  return this.reduce((acc, curr) => acc = acc.concat(curr))
}

const addressZip = person
  .get('addresses')
  .filter(address => address.get('legacy_id'))
  .filter(newAddress => getZIPErrors(newAddress.get('zip')))
  .concatAll()

推荐阅读