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

如何将MySQL查询返回的数组对象转换为指定格式的对象数据

解决方案

实现代码

const results = [{"id":230,"a":1,"b":0,"c":0},{"id":232,"a":1,"b":0,"c":0},{"id":234,"a":0,"b":1,"c":0},{"id":236,"a":1,"b":0,"c":0},{"id":238,"a":0,"b":1,"c":0},{"id":240,"a":0,"b":1,"c":0},{"id":242,"a":0,"b":0,"c":1}];

const bigRoad = {};
let currentColIndex = 1;
let currentColKey = `col${currentColIndex}`;
let currentActiveField = null;

// 初始化第一列
bigRoad[currentColKey] = {};

results.forEach(item => {
    // 提取当前项的有效字段(a/b/c中值为1的字段)
    const activeField = Object.keys(item).find(key => ['a', 'b', 'c'].includes(key) && item[key] === 1);
    
    if (!activeField) return; // 按规则不会出现,做容错处理
    
    // 规则3:遇到c字段直接累加到当前列
    if (activeField === 'c') {
        bigRoad[currentColKey][activeField] = (bigRoad[currentColKey][activeField] || 0) + 1;
        return;
    }
    
    // 处理a/b字段
    if (!currentActiveField) {
        // 第一条数据,设置当前列的活跃字段并初始化计数
        currentActiveField = activeField;
        bigRoad[currentColKey][activeField] = 1;
    } else if (activeField === currentActiveField) {
        // 和当前列活跃字段相同,累加计数
        bigRoad[currentColKey][activeField] += 1;
    } else {
        // 字段不同,新增一列
        currentColIndex++;
        currentColKey = `col${currentColIndex}`;
        currentActiveField = activeField;
        bigRoad[currentColKey] = { [activeField]: 1 };
    }
});

console.log(JSON.stringify(bigRoad, null, 2));

思路解释

  • 动态列管理:不再预先定义大量冗余列,通过currentColIndex动态生成col1、col2等列名,适配任意长度的输入数据。
  • 有效字段提取:利用find方法快速定位每条数据中值为1的a/b/c字段,契合规则1的约束。
  • 规则适配逻辑:
    • 针对c字段直接在当前列累加计数,不触发列新增(规则3);
    • 针对a/b字段,判断是否与当前列的活跃字段一致:一致则累加计数,不一致则新增列并重置活跃字段(规则2)。

结果验证

运行代码后输出如下(注:根据输入数据,最后一条c:1仅累加1次,与你提供的预期示例中c:2存在差异,推测是示例笔误):

{
  "col1": { "a": 2 },
  "col2": { "b": 1 },
  "col3": { "a": 1 },
  "col4": { "b": 2, "c": 1 }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 09:37:01