[英]How to I prevent the following map function from returning undefined objects?
I have a function loops through an array, rearranges its objects, and returns the result (excluding the current object): 我有一个函数遍历数组,重新排列其对象,并返回结果(不包括当前对象):
// buildings = [{ objectId: '1', objectId: '2', objectId: '3' }]
// currentBuilding = { objectId: '1' }
const result buildings.map(building => {
if (building.objectId === this.currentBuilding.objectId) {
return
}
return {
newField: building.objectId,
}
})
return result
I want it to return: 我希望它返回:
This function will return: 该函数将返回:
[{ newField: '2', newField: '3' }]
However, now I'm getting: 但是,现在我得到:
[{ undefined, newField: '2', newField: '3' }]
Why is this and how to fix it? 为什么会这样以及如何解决?
You can't, but you can filter out the offending item: 您不能,但是您可以过滤出有问题的项目:
const result buildings.filter(b => b.objectId !== this.currentBuilding.objectId)
.map(b => ({newField: b.objectId});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.