You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用filter+find匹配数组对象时如何保留item.units原始顺序?

解决方案

你当前代码用filter遍历this.units,结果顺序由this.units决定。要保持item.units的原有顺序,得反过来以item.units为基准遍历匹配:

修改后的代码

previewSectionInfo(item) {
    // 按item.units的原有顺序匹配完整单元信息
    const sectionsUnits = item.units.map(unitItem => {
        return this.units.find(u => u.id === unitItem.id);
    }).filter(Boolean); // 过滤掉未匹配到的项(可选)
    item.units = sectionsUnits;
}

关键说明

  • 用map遍历item.units,确保结果顺序和原ID数组完全一致
  • 每个元素通过find从this.units中匹配对应完整信息
  • filter(Boolean)用于排除在this.units中找不到的ID(如果不需要可以去掉)

如果item.units里存的是纯ID值(不是带id属性的对象),代码可以简化:

previewSectionInfo(item) {
    const sectionsUnits = item.units.map(id => {
        return this.units.find(u => u.id === id);
    }).filter(Boolean);
    item.units = sectionsUnits;
}

内容的提问来源于stack exchange,提问作者Jason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 09:53:38