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

如何在Node.js或MySQL中处理查询结果,生成含分组照片的JSON结构

两种方案实现用户照片数组的JSON结构转换

你可以通过MySQL查询调整或者Node.js代码处理两种方式实现需求,下面分别说明:

一、MySQL查询调整方案

直接在查询时合并同一用户的照片,返回聚合后的结果:

SELECT 
  user_Id,
  name,
  age,
  GROUP_CONCAT(photo SEPARATOR '|') AS photos
FROM your_table_name
GROUP BY user_Id, name, age;

注意事项:

  • 这里用|作为分隔符,避免和photo内容里的逗号冲突,你可以根据实际内容选更合适的分隔符
  • 默认GROUP_CONCAT有长度限制(1024字节),如果照片数量多或内容长,需要先执行SET group_concat_max_len = 102400;调整限制

拿到查询结果后,在Node.js里把photos字段按分隔符拆成数组即可:

// 假设db.query返回的结果是queryResult
const result = queryResult.map(item => ({
  user_id: item.user_Id,
  name: item.name,
  age: item.age,
  photo: item.photos.split('|')
}));

// 转成你需要的键为0、1的对象格式
const finalResult = Object.fromEntries(result.map((user, index) => [index, user]));

二、Node.js代码处理方案

直接查询原始的5条数据,在Node.js里用reduce合并同一用户的照片:

// 假设从MySQL拿到的原始数据是rawData
const rawData = [
  { user_Id: 1, name: 'Zack', age: 23, photo: 'Blob[2.1]' },
  { user_Id: 1, name: 'Zack', age: 23, photo: 'Blob[3.3]' },
  { user_Id: 1, name: 'Zack', age: 23, photo: 'Blob[1.9]' },
  { user_Id: 3, name: 'Amy', age: 19, photo: 'Blob[2.9]' },
  { user_Id: 3, name: 'Amy', age: 19, photo: 'Blob[3.3]' }
];

// 合并数据
const mergedData = rawData.reduce((acc, current) => {
  // 查找已存在的用户
  const user = acc.find(u => u.user_id === current.user_Id);
  if (user) {
    // 存在则追加照片
    user.photo.push(current.photo);
  } else {
    // 不存在则新增用户,照片存为数组
    acc.push({
      user_id: current.user_Id,
      name: current.name,
      age: current.age,
      photo: [current.photo]
    });
  }
  return acc;
}, []);

// 转成目标JSON格式
const finalResult = Object.fromEntries(mergedData.map((item, idx) => [idx, item]));

方案对比与建议

  • 选MySQL方案:如果照片内容无特殊分隔符、数量不多,能减少Node.js处理逻辑,降低数据传输量,效率更高
  • 选Node.js方案:如果需要对照片做复杂处理(比如过滤、格式转换),或者照片内容可能包含分隔符,或者照片数量多(避免GROUP_CONCAT长度限制),灵活性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:05:31