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

如何从JSON中获取版本匹配current_fish_version的鱼名称?

获取匹配当前版本的鱼名称实现方案

给定JSON数据:

{
    "fish": [
        {
            "name": "pike",
            "version": 1
        },
        {
            "name": "haddock",
            "version": 2
        }
    ],
    "current_fish_version": 2
}

以下是几种常用语言的实现方式:

JavaScript实现

利用数组的find方法快速定位首个匹配项,同时处理无匹配的情况:

const data = {
    "fish": [
        { "name": "pike", "version": 1 },
        { "name": "haddock", "version": 2 }
    ],
    "current_fish_version": 2
};

const matchedFish = data.fish.find(fish => fish.version === data.current_fish_version);
const fishName = matchedFish ? matchedFish.name : '未找到匹配的鱼';

console.log(fishName); // 输出: haddock

如果需要获取所有版本匹配的鱼名称,改用filter+map组合:

const allMatchedNames = data.fish
  .filter(fish => fish.version === data.current_fish_version)
  .map(fish => fish.name);

console.log(allMatchedNames); // 输出所有匹配名称组成的数组

Python实现

用next()函数配合生成器表达式查找首个匹配项,兼容无匹配场景:

data = {
    "fish": [
        {"name": "pike", "version": 1},
        {"name": "haddock", "version": 2}
    ],
    "current_fish_version": 2
}

matched_fish = next((fish for fish in data["fish"] if fish["version"] == data["current_fish_version"]), None)
fish_name = matched_fish["name"] if matched_fish else "未找到匹配的鱼"

print(fish_name)  # 输出: haddock

要获取所有匹配的鱼名称,直接用列表推导式:

all_matched_names = [fish["name"] for fish in data["fish"] if fish["version"] == data["current_fish_version"]]
print(all_matched_names)  # 输出所有匹配名称组成的列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 21:33:23