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

Vue路由跳转时如何过滤数组对象,仅传递指定字段至目标页面

问题

现有代码会将this.Items中的完整对象存入HistoryData数组,再跳转至名为“History”的页面:

let HistoryData = [];
for (const [key, value] of Object.entries(this.Items)) {
  HistoryData.push(value)  
}
this.$router.push({ name: "History" });

但需求改为:仅传递每个对象中的Code、AccNumber、InvNum三个字段,形成包含多个对象的数组,排除billDate和billingAddress等其他字段。

待过滤的原始数据示例:

[
    {
        "InvNum": "X34343",
        "billDate": "2022-05-31T00:00:00Z",
        "billingAddress": "Address 6",
        "Code": "CCN",
        "AccNumber": "2343456"
    },
    {
        "InvNum": "5464564",
        "billDate": "2022-05-31T00:00:00Z",
        "billingAddress": "Address 5",
        "Code": "g",
        "AccNumber": "556"
    },
    {
        "InvNum": "45",
        "billDate": "2022-05-31T00:00:00Z",
        "billingAddress": "Address 4",
        "Code": "d",
        "AccNumber": "hj5656"
    },
    {
        "InvNum": "567",
        "billDate": "2022-05-31T00:00:00Z",
        "billingAddress": "Address 3",
        "Code": "j",
        "AccNumber": "ghg4545"
    },
    {
        "InvNum": "86667",
        "billDate": "2022-05-31T00:00:00Z",
        "billingAddress": "Address 2",
        "Code": "k",
        "AccNumber": "sddf4545"
    },
    {
        "InvNum": "44534",
        "billDate": "2022-05-31T00:00:00Z",
        "billingAddress": "Address 1",
        "Code": "y",
        "AccNumber": "fgfg556"
    }
]
解决方案

可以通过两种方式实现字段过滤,以下是具体代码:

方式一:用Array.map()简化处理

如果this.Items本身是数组,直接用map遍历并构造仅包含目标字段的新对象:

// 过滤出指定字段的对象数组
const HistoryData = this.Items.map(item => ({
  Code: item.Code,
  AccNumber: item.AccNumber,
  InvNum: item.InvNum
}));

// 跳转时携带处理后的数据(需转成字符串传递)
this.$router.push({ 
  name: "History",
  query: { historyData: JSON.stringify(HistoryData) }
});

方式二:修改原有循环逻辑

如果要保留原for...of循环写法,在推入数组时构造新对象即可:

let HistoryData = [];
for (const [key, value] of Object.entries(this.Items)) {
  // 只提取需要的三个字段
  const filteredItem = {
    Code: value.Code,
    AccNumber: value.AccNumber,
    InvNum: value.InvNum
  };
  HistoryData.push(filteredItem);
}

this.$router.push({ 
  name: "History",
  query: { historyData: JSON.stringify(HistoryData) }
});

接收数据说明

在History页面接收数据时,需要将字符串转回数组:

// History页面内解析数据
const receivedData = JSON.parse(this.$route.query.historyData);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:55:15