Swift 3:基于id匹配更新字典数组中的键值对
嘿,我来帮你搞定这个两个JSON数组关联更新的问题!核心思路是先把第二个数组转成以id为键的映射表,这样查找对应条目时效率超高,再遍历第一个数组完成信息补充。
核心步骤
- 把
JSONResponse2转换成以id为键的字典/对象,这样查找对应id的条目只需要O(1)时间,比嵌套循环遍历高效太多 - 遍历
JSONResponse1的每个条目,检查当前条目的id是否在映射表中 - 如果存在匹配的id,就把
JSONResponse2里的地址信息合并到当前条目;如果不存在,保持原条目不变
Python实现示例
假设你用Python处理,代码如下:
# 模拟从URL获取的两个JSON响应数组 response1 = [ {"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie"} ] response2 = [ {"id": 1, "address": "123 Main St"}, {"id": 3, "address": "456 Oak Ave"} ] # 将response2转为id映射字典,快速查找 response2_id_map = {item["id"]: item for item in response2} # 遍历更新response1 for item in response1: item_id = item["id"] if item_id in response2_id_map: # 方式1:仅更新address字段(推荐,避免覆盖其他字段) item["address"] = response2_id_map[item_id]["address"] # 方式2:合并所有字段(response2的字段会覆盖response1同名字段) # item.update(response2_id_map[item_id]) print(response1)
运行后response1会变成:
[ {"id": 1, "name": "Alice", "address": "123 Main St"}, {"id": 2, "name": "Bob"}, {"id": 3, "name": "Charlie", "address": "456 Oak Ave"} ]
JavaScript实现示例
如果是前端场景用JS,思路完全一致:
// 模拟两个JSON响应数组 const response1 = [ {id: 1, name: "Alice"}, {id: 2, name: "Bob"}, {id: 3, name: "Charlie"} ]; const response2 = [ {id: 1, address: "123 Main St"}, {id: 3, address: "456 Oak Ave"} ]; // 构建id映射表 const response2Map = response2.reduce((map, item) => { map[item.id] = item; return map; }, {}); // 生成更新后的数组 const updatedResponse1 = response1.map(item => { const matched = response2Map[item.id]; // 合并条目,matched存在则补充地址,否则返回原条目 return matched ? {...item, ...matched} : item; }); console.log(updatedResponse1);
为什么这么做?
用映射表替代嵌套循环,当数组规模较大时,性能会有质的提升——嵌套循环是O(n*m)的时间复杂度,而映射表查找是O(1),整体复杂度降到O(n+m),处理上万条数据时差异特别明显。
内容的提问来源于stack exchange,提问作者Kanav Batra
相关产品推荐
相关产品推荐

