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

如何无需遍历嵌套对象列表提取interesting_key对应值?

嘿,我懂你不想手动写多层嵌套循环来处理这个结构的心情,这就给你两个省心的解决方案,不用你挨个遍历每个对象列表:

提取嵌套结构中所有interesting_key的值

方案1:原生递归函数(无需额外依赖)

这个方案用递归自动处理所有嵌套层级,你只需要定义一次逻辑,不用手动处理每一层的list_of_objects:

JavaScript 实现

function extractInterestingKeys(obj) {
  let results = [];
  
  // 检查当前对象是否有目标键,有就加入结果
  if (obj.interesting_key) {
    results.push(obj.interesting_key);
  }
  
  // 如果当前对象包含子列表,递归处理每个子元素
  if (obj.list_of_objects) {
    obj.list_of_objects.forEach(item => {
      results = results.concat(extractInterestingKeys(item));
    });
  }
  
  return results;
}

// 测试你的数据
const yourData = { 
  "list_of_objects" : [ 
    { "name" : "0", "interesting_key" : "some_value" }, 
    { 
      "name" : "1", 
      "interesting_key" : "some_other_value", 
      "list_of_objects" : [ 
        { "name" : "10", "interesting_key" : "something" }, 
        { "name" : "11" } 
      ] 
    }, 
    { "name" : "2", "interesting_key" : "again_some_other_value" } 
  ] 
};

console.log(extractInterestingKeys(yourData));
// 输出: ["some_value", "some_other_value", "something", "again_some_other_value"]

Python 实现

def extract_interesting_keys(obj):
    results = []
    
    # 检查当前字典是否包含目标键
    if 'interesting_key' in obj:
        results.append(obj['interesting_key'])
    
    # 递归处理子列表
    if 'list_of_objects' in obj:
        for item in obj['list_of_objects']:
            results.extend(extract_interesting_keys(item))
    
    return results

your_data = { 
  "list_of_objects" : [ 
    { "name" : "0", "interesting_key" : "some_value" }, 
    { 
      "name" : "1", 
      "interesting_key" : "some_other_value", 
      "list_of_objects" : [ 
        { "name" : "10", "interesting_key" : "something" }, 
        { "name" : "11" } 
      ] 
    }, 
    { "name" : "2", "interesting_key" : "again_some_other_value" } 
  ] 
}

print(extract_interesting_keys(your_data))
# 输出: ['some_value', 'some_other_value', 'something', 'again_some_other_value']

方案2:用JSONPath声明式提取(更简洁)

如果允许使用第三方库,JSONPath是更优雅的选择——它用类似XPath的语法,一句话就能提取所有层级的interesting_key值,完全不用写遍历逻辑:

JavaScript 实现(使用jsonpath-plus库)

先安装依赖:

npm install jsonpath-plus

然后编写代码:

const jp = require('jsonpath-plus');

const yourData = { /* 你的数据 */ };
const results = jp.query(yourData, '$..interesting_key');
console.log(results);
// 直接得到目标数组

这里的$..interesting_key表示:在整个JSON结构的所有层级中,提取所有interesting_key对应的值。

Python 实现(使用jsonpath-ng库)

先安装依赖:

pip install jsonpath-ng

然后编写代码:

from jsonpath_ng import parse

your_data = { /* 你的数据 */ }
jsonpath_expr = parse('$..interesting_key')
results = [match.value for match in jsonpath_expr.find(your_data)]
print(results)
# 同样得到目标数组

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 07:22:51