我有一个有机会的数据结构,每个机会都有笔记。我想把与一个人有关的所有机会都记录下来,并展示出来。现在我有了下面的内容,这是可行的。但是,我想的是必须有一种更简单的方法,在这里我不能拥有外部数组,而是从opportunityNotesList返回与opportunityNotesList()相同的结果。
const thisNotes = {}
const opportunityNotesList = _(opportunities)
.map((opportunity, id) => ({id, ...opportunity}))
.filter(opportunity => opportunity.linkToContact === id)
.map(opportunity => {
_(opportunity.notes)
.map((note, id) => ({id, ...note}))
.each(note => {
thisNotes[`${note.id}`] = note
})
})真的只是在寻找一种更优雅的方式来完成这个查询。
发布于 2016-12-04 05:29:13
使用_.flatMap避免嵌套循环
const thisNotes = _(opportunities)
.filter({linkToContact: id})
.flatMap('notes')
// way 1 - if id is really necessary
.map((note, id) => ({id, ...note}))
.keyBy('id')
// way 2 - if id is unnecessary
.reduce(function(result, note, id) {
result[id] = note;
return result;
}, {});发布于 2016-12-04 04:04:04
我建议你不要太优雅。我已经很难跟踪上面的代码了,想象一下另一个开发人员必须把它捡起来并进行更改!
将它分离出它自己的助手,或者更好的选择器(例如使用reselect )。
我同意,随着时间的推移,这种转变变得相当痛苦--这是我似乎一直在头上碰到的一件事。
https://stackoverflow.com/questions/40955076
复制相似问题