javascript - 仅当数组存在时 lodash 映射数据

标签 javascript lodash

我需要编写一个小函数,它获取两个对象的值并将它们存储到一个数组中,然后我将其合并为一个数据数组。

问题是其中一个数组可能不存在,所以它应该只返回一个空数组,这样合并就不会报错。

let active = _.map(this.modalData.currentExceptions.activeExceptions.active, 'QID');
let future = _.map(this.modalData.currentExceptions.futureExceptions.future, 'QID')
let combined = _.merge(active, future);

在这种情况下,futureExceptions 不是此数据集中的数组,因此 map 会抛出 undefiend 错误。

有什么我可以添加到这个 中的吗?如果找不到键/对象,map 将返回一个空数组?

最佳答案

您可以使用 _.get .它允许您在键解析为 undefined 时设置默认值。

let active = _.map(
  _.get(
    this.modalData.currentExceptions.activeExceptions, 'active', []
  ), 
  'QID'
);

let future = _.map(
  _.get(
    this.modalData.currentExceptions.futureExceptions, 'future', []
  ),
  'QID'
)

let combined = _.merge(active, future);

关于javascript - 仅当数组存在时 lodash 映射数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46457818/

相关文章:

javascript - lodash:使用不同的对象数组过滤对象数组

javascript - 有没有办法制作不可编辑的跨度?

javascript - 更简单的 ParseInt 方法

javascript - 使用 lodash javascript 过滤子集合

google-apps-script - 为什么 loadash concat instanceof Array 在 google apps 脚本包含的库中为 false

javascript - 函数式编程 : Return first truthy result of calling a list of different functions with a specific argument

javascript - 使用 prevAll() 时选择时无法正确更新值

javascript - 使用 JavaScript 将工作 PHP 文件(带有脚本)拉入 div,无需使用 iframe

javascript 图表 - 带有两个 Y 轴的 nvd3 折线图

javascript - 限制dumb组件中的 react 事件处理程序