我有一个简单的函数,我希望进一步简化它:
setAreas() {
this.areas = ipcRenderer.sendSync('request', 'areas').map(_area => {
_area.locations = _area.locations.map(locationId => this.getLocation(locationId))
return _area
})
}
有没有办法通过在 _area.locations
上执行 map 并返回更新的 _area
来将其减少到一行?
最佳答案
一种选择是使用Object.assign
,它将返回分配给的基础对象:
setAreas() {
this.areas = ipcRenderer.sendSync('request', 'areas').map(_area => (
Object.assign(_area, { locations: _area.locations.map(locationId => this.getLocation(locationId)) })
));
}
但这不太可读。我更喜欢你当前的代码。
请注意,.map
适用于将一个数组转换为另一个数组的情况。在这里,您只需改变现有数组中的每个对象; forEach
更合适:
setAreas() {
this.areas = ipcRenderer.sendSync('request', 'areas');
this.areas.forEach((a) => a.locations = a.locations.map(locationId => this.getLocation(locationId)))
}
如果getLocation
只接受一个参数,你就可以打高尔夫球
a.locations = a.locations.map(locationId => this.getLocation(locationId))
下降到
a.locations = a.locations.map(this.getLocation.bind(this))
(如果不需要 this
上下文,您甚至可以删除 .bind(this)
)
关于javascript - 如何对对象的元素执行映射功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54414243/