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

如何遍历JSON对象并统计指定Key的唯一值数量?

日志文件统计与结构转换解决方案

问题描述

原始日志文件结构

每个JSON日志文件的正确结构如下(已修正示例中的语法错误,外层id需与logs同级):

{
  "logs": [
    {
      "id": "12321321321321",
      "email": "test@email.com",
      "message": "ahahaha"
    },
    {
      "id": "12321321312",
      "email": "test@email.com",
      "message": "hahahaha."
    }
  ],
  "id": "12321321321"
}

目标输出结构

需要将每个日志文件转换为如下格式的对象:

{
  "hello_id": "外层id值",
  "array": [
    {
      "email": "test@email.com",
      "total": 2
    }
  ]
}

已实现基础代码

目前已完成目录下JSON文件的遍历与读取解析:

jsonsInDirectory.forEach((file) => {
  const fileData = fs.readFileSync(path.join("./logs", file), "utf8");
  const jsonData = JSON.parse(fileData);
});

需求:基于现有代码,完成logs数组内的邮箱出现次数统计,并生成目标结构的对象。

解决方案

通过邮箱计数统计和目标结构组装两步即可完成需求,具体代码修改如下:

完整实现代码

const fs = require('fs');
const path = require('path');

// 假设jsonsInDirectory是已获取的目录下JSON文件名数组
jsonsInDirectory.forEach((file) => {
  const fileData = fs.readFileSync(path.join("./logs", file), "utf8");
  const jsonData = JSON.parse(fileData);

  // 1. 统计每个邮箱的出现次数
  const emailCount = {};
  jsonData.logs.forEach(logItem => {
    const email = logItem.email;
    emailCount[email] = (emailCount[email] || 0) + 1;
  });

  // 2. 将统计结果转换为目标数组格式
  const resultArray = Object.entries(emailCount).map(([email, total]) => ({
    email,
    total
  }));

  // 3. 组装最终目标对象
  const finalResult = {
    hello_id: jsonData.id,
    array: resultArray
  };

  // 可根据需求处理结果,比如打印、写入文件等
  console.log(finalResult);
});

代码说明

  • 邮箱统计:用emailCount对象记录每个邮箱的出现次数,遍历logs数组时直接更新计数,简化写法(emailCount[email] || 0) + 1处理首次出现的邮箱。
  • 结构转换:通过Object.entries将统计对象转为键值对数组,再映射为目标格式的对象数组。
  • 结果组装:直接提取外层id作为hello_id字段值,将转换后的数组赋值给array字段,得到最终结构。

注意事项

  • 确保原始JSON文件语法正确,避免解析报错。
  • 若处理大量文件,建议改用fs.readFile异步方法,避免阻塞主线程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:27:20