使用BOTH筛选器和查找功能时获取数组的原始顺序

huangapple go评论66阅读模式
英文:

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:&quot;one&quot;},
  {id:2,name:&quot;two&quot;},
  {id:3,name:&quot;three&quot;},
  {id:4,name:&quot;four&quot;},
  {id:5,name:&quot;five&quot;}
 ];

function previewSectionInfo() {
  const specificUnits = item.units.map(
    function(unitID){
      return this.units.find(el =&gt; 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 =&gt; {
    return Object.assign(...this.units.filter(i =&gt; i.id == p.id))
})

huangapple
  • 本文由 发表于 2023年3月15日 21:05:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75745141.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定