JavaScript如何读取JSON动态键并筛选current为true的用户配置
解决方案
完全可以跳过未知的随机ID键完成筛选,核心思路是提取profiles字段下的所有属性值,忽略随机键名后过滤current为true的对象即可。
通用实现步骤
- 读取API返回数据中的
profiles字段内容 - 获取
profiles对象的所有属性值,无需关注随机生成的键名 - 遍历属性值列表,筛选出
current字段为true的对象,即为目标当前配置文件
常见语言实现示例
JavaScript
// 假设apiResponse为接口返回的JSON解析后对象 const profiles = apiResponse.profiles; // 提取所有配置文件对象,自动忽略随机ID键 const allProfiles = Object.values(profiles); // 筛选出当前生效的配置文件 const currentProfile = allProfiles.find(profile => profile.current === true); // 直接使用currentProfile即可访问所有配置字段 console.log(currentProfile.cute_name); // 输出示例:Pomegranate
Python
# 假设api_response为接口返回解析后的字典 profiles = api_response["profiles"] # 提取所有配置文件对象 all_profiles = list(profiles.values()) # 筛选当前生效的配置文件 current_profile = [p for p in all_profiles if p["current"]][0] # 访问配置字段示例 print(current_profile["cute_name"]) # 输出示例:Pomegranate
如果业务场景可能存在多个生效配置,将JS的find方法替换为filter,删除Python列表推导取下标[0]的逻辑,即可拿到所有符合要求的配置列表。
内容的提问来源于stack exchange,提问作者Cédric
相关产品推荐
相关产品推荐

