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

如何根据值获取父分支?筛选价格为12的水果名称

筛选关联价格为12的水果名称

实现思路

要找到所有关联价格为12的水果名称,核心分两步:

  • 从水果数组里筛选出包含价格为"12"的国家的水果对象
  • 从这些对象中提取对应的水果名称

JavaScript 实现示例

假设你的JSON数据已经解析为JS对象,可通过数组方法链式调用完成需求:

const data = {
    "fruits": [
        {
            "name": "apple",
            "countries": [
                {
                    "name": "japan",
                    "price": "12"
                },
                {
                    "name": "iceland",
                    "price": "83"
                }
            ]
        },
        {
            "name": "oranges",
            "countries": [
                {
                    "name": "germany",
                    "price": "344"
                },
                {
                    "name": "italy",
                    "price": "99"
                }
            ]
        }
    ]
};

// 筛选符合条件的水果并提取名称
const targetFruits = data.fruits
    .filter(fruit => fruit.countries.some(country => country.price === "12"))
    .map(fruit => fruit.name);

console.log(targetFruits); // 输出: ["apple"]

关键方法说明

  • filter():遍历水果数组,只保留满足条件的水果对象
  • some():检查当前水果的国家列表中,是否至少有一个国家的价格等于"12"(注意原数据中price是字符串类型,需用严格相等匹配)
  • map():将筛选后的水果对象转换为仅包含名称的数组

Python 实现示例

如果用Python处理,可通过列表推导式快速完成:

data = {
    "fruits": [
        {
            "name": "apple",
            "countries": [
                {"name": "japan", "price": "12"},
                {"name": "iceland", "price": "83"}
            ]
        },
        {
            "name": "oranges",
            "countries": [
                {"name": "germany", "price": "344"},
                {"name": "italy", "price": "99"}
            ]
        }
    ]
}

target_fruits = [fruit["name"] for fruit in data["fruits"] if any(country["price"] == "12" for country in fruit["countries"])]
print(target_fruits)  # 输出: ['apple']

逻辑说明

  • 列表推导式直接遍历水果数组,用any()判断当前水果是否存在价格为"12"的国家,满足条件则提取名称

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 23:36:05