英文:
Get the original order of the array when using BOTH filter with find
问题
我有两个对象数组。
a)this.units(保存有关单位的所有信息)
b)item.units(仅保存正在使用的单位的ID)
我试图将完整的单位与单位ID匹配起来。下面的方法有效,但它会打乱单位的原始顺序。
item.unit 将具有一个按特定顺序排列的单位ID数组,比如 1,2,3,4
然后,我需要将来自 this.units 的完整单位附加到 item.unit,但保持相同的顺序 1,2,3,4
这段代码将完整的单位与项目单位匹配,但它使用的是 this.units 而不是 item.unit 的顺序,因此最终结果可能是 4,2,1,3
previewSectionInfo(item) {
const sectionsUnits = this.units.filter((u) => {
return item.units.find(el => el.id == u.id)
})
item.units = sectionsUnits
}
英文:
I have two array's of objects.
a) this.units (holds ALL the info on the units)
b) item.units (holds just the IDs of the units being used)
I am trying to match up the full unit with the unit id. The method below works but it puts the units out of their original order.
The item.unit will have an array of unit ids in a specific order lets say 1,2,3,4
I then need to attach the full unit from this.units to the item.unit but keep the same order 1,2,3,4
This code matches the full unit to the item unit but it uses the order from this.units not item.unit so the end results is something like 4,2,1,3
previewSectionInfo(item) {
const sectionsUnits = this.units.filter((u) => {
return item.units.find(el => el.id == u.id)
})
item.units = sectionsUnits
}
答案1
得分: 2
我认为我应该使用 map()
遍历 item.unit
(保持其顺序),并返回来自 this.units
的相应记录。
const specificUnits = item.units.map(
function(unitID){
return this.units.find(el => el.id == unitID);
}
)
console.log(specificUnits);
英文:
I think I would instead map()
over item.unit
(keeping its order) and return the corresponding record from this.units
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const item = {};
item.units = [1,3,5];
//const thiss = {};
this.units = [
{id:1,name:"one"},
{id:2,name:"two"},
{id:3,name:"three"},
{id:4,name:"four"},
{id:5,name:"five"}
];
function previewSectionInfo() {
const specificUnits = item.units.map(
function(unitID){
return this.units.find(el => el.id == unitID);
}
)
console.log(specificUnits);
}
previewSectionInfo();
<!-- end snippet -->
答案2
得分: 0
刚刚找到答案。对于其他有这个问题的人,这是我现在的代码:
const sectionsUnits = item.units.map(p => {
return Object.assign(...this.units.filter(i => i.id == p.id))
})
英文:
Just found the answer. For anyone else out there having this problem here is what I now have:
const sectionsUnits = item.units.map(p => {
return Object.assign(...this.units.filter(i => i.id == p.id))
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论