如何从咖啡馆列表与类型列表两个数据对象中获取对应关联值
解决咖啡馆类型匹配问题的实现方案
这是个很常见的数据映射匹配需求,核心思路是先把类型列表转换成键值对形式的字典(映射表),这样就能快速通过咖啡馆的type编码找到对应的类型名称,避免每次匹配都遍历整个类型列表,效率更高。
假设完整的输入数据
首先我补全你没写完的类型列表数据(符合你给出的结构):
// 咖啡馆列表 { "list": { "item": [ { "ID": "31", "name": "Staut", "type": "1" }, { "ID": "34", "name": "Pinta", "type": "3" } ] } } // 咖啡馆类型列表 { "list": { "item": [ { "typeId": "1", "typeName": "Espresso Bar" }, { "typeId": "2", "typeName": "Bakery Cafe" }, { "typeId": "3", "typeName": "Bar" } ] } }
JavaScript 实现示例
// 定义输入数据 const cafes = { "list": { "item": [ { "ID": "31", "name": "Staut", "type": "1" }, { "ID": "34", "name": "Pinta", "type": "3" } ] } }; const cafeTypes = { "list": { "item": [ { "typeId": "1", "typeName": "Espresso Bar" }, { "typeId": "2", "typeName": "Bakery Cafe" }, { "typeId": "3", "typeName": "Bar" } ] } }; // 1. 构建类型映射表:{ 类型编码: 类型名称 } const typeMap = cafeTypes.list.item.reduce((map, typeItem) => { map[typeItem.typeId] = typeItem.typeName; return map; }, {}); // 2. 遍历咖啡馆列表,匹配类型并整理结果 const matchedCafes = cafes.list.item.map(cafe => ({ cafeId: cafe.ID, cafeName: cafe.name, typeCode: cafe.type, typeName: typeMap[cafe.type] || "Unknown Type" // 处理找不到匹配类型的情况 })); // 输出结果 console.log(matchedCafes);
运行后会得到如下结果:
[ { cafeId: '31', cafeName: 'Staut', typeCode: '1', typeName: 'Espresso Bar' }, { cafeId: '34', cafeName: 'Pinta', typeCode: '3', typeName: 'Bar' } ]
Python 实现示例
如果你用后端语言处理,Python版本的实现如下:
# 定义输入数据 cafes = { "list": { "item": [ {"ID": "31", "name": "Staut", "type": "1"}, {"ID": "34", "name": "Pinta", "type": "3"} ] } } cafe_types = { "list": { "item": [ {"typeId": "1", "typeName": "Espresso Bar"}, {"typeId": "2", "typeName": "Bakery Cafe"}, {"typeId": "3", "typeName": "Bar"} ] } } # 1. 构建类型映射表 type_map = {item["typeId"]: item["typeName"] for item in cafe_types["list"]["item"]} # 2. 匹配并生成结果 matched_cafes = [ { "cafe_id": cafe["ID"], "cafe_name": cafe["name"], "type_code": cafe["type"], "type_name": type_map.get(cafe["type"], "Unknown Type") } for cafe in cafes["list"]["item"] ] # 打印结果 print(matched_cafes)
运行后输出:
[ {'cafe_id': '31', 'cafe_name': 'Staut', 'type_code': '1', 'type_name': 'Espresso Bar'}, {'cafe_id': '34', 'cafe_name': 'Pinta', 'type_code': '3', 'type_name': 'Bar'} ]
核心思路说明
- 构建映射表:用
reduce(JS)或字典推导式(Python)把类型列表转换成键值对,这样查找类型名称的时间复杂度是O(1),比每次遍历类型列表的O(n)高效得多,数据量大的时候优势明显。 - 容错处理:用
||(JS)或dict.get()(Python)设置默认值,避免因为咖啡馆的type编码在类型列表中不存在而出现undefined或KeyError。
内容的提问来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

