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

如何统计JSON树结构中指定键的出现次数?

统计JSON结构中指定键的出现次数

JavaScript没有原生的类似XPath的工具可以直接查询JSON数据结构中指定键的出现次数,必须通过递归遍历整个数据结构来实现。

下面是一个实现该功能的简单函数:

function countKeyOccurrences(data, targetKey) {
  let count = 0;
  // 处理对象类型
  if (typeof data === 'object' && data !== null && !Array.isArray(data)) {
    for (const key of Object.keys(data)) {
      if (key === targetKey) {
        count++;
      }
      // 递归处理当前键对应的值
      count += countKeyOccurrences(data[key], targetKey);
    }
  }
  // 处理数组类型
  else if (Array.isArray(data)) {
    for (const item of data) {
      count += countKeyOccurrences(item, targetKey);
    }
  }
  // 基本类型直接返回当前计数
  return count;
}

用你提供的JSON数据测试:

const jsonData = {
 "a": {"b": "value"},
 "c": {"b": "value"},
 "d": {"b": "value"}, 
 "e": {"e": {"b": ["value"]}}
};

console.log(countKeyOccurrences(jsonData, 'b')); // 输出:4

这个函数会遍历所有嵌套的对象和数组,统计所有匹配目标键的出现次数,完全覆盖你给出的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 08:30:53