使用Mobx,我尝试按照future.cancel(true);
中scheduleTaskExecutor.shutdown();
的顺序输出booksByIdMap
中的图书标题:
booksSortedIdArray
class BookStore {
@observable booksSortedIdArray = ["88cd7621", "88cd7624", "88cd7623", "88cd7622"];
@observable booksByIdMap = asMap({
"88cd7621": {
"id": "88cd7621",
"title": "The Secret"
},
"88cd7622": {
"id": "88cd7622",
"title": "The Alchemist"
},
"88cd7623": {
"id": "88cd7623",
"title": "Javascript"
},
"88cd7624": {
"id": "88cd7624",
"title": "PHP"
}
});
@computed get byBookId() {
return this.booksByIdMap.values().filter(b => this.booksSortedIdArray.includes(b.id));
}
}
中的filter
似乎没有维持该排序顺序而是输出:
byBookId
而不是:
The Secret, The Alchemist, Javascript, PHP
这是fiddle。
如何根据The Secret, PHP, Javascript, The Alchemist
中的ID排序顺序输出标题?
答案 0 :(得分:1)
您可以在数组上使用reduce,并尝试从地图中get
每个键。如果存在,只需将其添加到结果中即可。 This way you will get it in order:
class BookStore {
@observable booksSortedIdArray = ["88cd7621", "88cd7624", "88cd7623", "88cd7622"];
@observable booksByIdMap = asMap({
"88cd7621": {
"id": "88cd7621",
"title": "The Secret"
},
"88cd7622": {
"id": "88cd7622",
"title": "The Alchemist"
},
"88cd7623": {
"id": "88cd7623",
"title": "Javascript"
},
"88cd7624": {
"id": "88cd7624",
"title": "PHP"
}
});
@computed get byBookId() {
return this.booksSortedIdArray.reduce((res, el) => {
const book = this.booksByIdMap.get(el);
if(book) {
res.push(book);
}
return res;
}, []);
}
}