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

ReactJS:移除对象键名及packingLocation值中的‘PACK - ’前缀

解决方案:移除键名与packingLocation中的"PACK - "前缀

当然可以实现,只需要遍历原数据结构,分别处理对象的键名和每个item的packingLocation属性即可,以下是具体实现:

1. 转换数据结构

先把categorizedDataFoods2转换为符合需求的结构——键名和packingLocation只保留A/B:

// 转换原数据,移除所有"PACK - "前缀
const transformedData = Object.fromEntries(
  Object.entries(categorizedDataFoods2).map(([originalKey, group]) => {
    // 处理对象键名,提取A/B部分
    const newKey = originalKey.replace('PACK - ', '');
    // 处理每个item的packingLocation属性
    const updatedItems = group.items.map(item => ({
      ...item,
      packingLocation: item.packingLocation.replace('PACK - ', '')
    }));
    // 返回处理后的键值对
    return [newKey, { ...group, items: updatedItems }];
  })
);

转换后的transformedData结构会变成:

{
    "A": {
        "items": [
            {
                "Category": "BREAKFAST",
                "Name": "Bacon (300g)",
                "Quantity": "1",
                "Weight": "0.400",
                "packingLocation": "A",
                "bought": false,
                "packed": false,
                "id": "T2ajRjW7uahiFm2NLspG"
            }
        ]
    },
    "B": {
        "items": [
            {
                "Category": "BREAKFAST",
                "Name": "Blueberries",
                "Quantity": "1",
                "Weight": 0.125,
                "packingLocation": "B",
                "bought": false,
                "packed": false,
                "id": "76412f40-15da-11ec-b278-b1ac8c1941a3"
            }
        ]
    }
}

2. 使用转换后的数据进行过滤

此时再用你原来的过滤逻辑,就能正常获取结果了:

const filteredItemsF = transformedData[key]?.items.filter(item => item.packingLocation === location);

补充说明

  • 上述代码不会修改原categorizedDataFoods2对象,而是生成一个新的转换后对象,避免污染原始数据。
  • 如果需要直接修改原对象,可以把逻辑调整为遍历原对象的键并直接更新,但不推荐这种方式,容易引发意外的副作用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 20:53:11