我需要编写一个小函数,它获取两个对象的值并将它们存储到一个数组中,然后我将其合并为一个数据数组。
问题是其中一个数组可能不存在,所以它应该只返回一个空数组,这样合并就不会报错。
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/