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

Excel转JSON格式调整需求:合并多对象为单对象多值结构

解决方案:将Excel转成单对象多IMEI的JSON结构

核心思路

读取Excel数据后,提取所有有效IMEI值并整合成一个数组,再封装到仅包含imei字段的单个对象中,替代原来每个IMEI对应一个独立对象的数组结构。

代码实现(基础版,手动指定列索引)

假设你的Excel中IMEI值位于第一列(索引0),表头在第一行,修改后的代码如下:

import readXlsxFile from 'read-excel-file'

const input = document.getElementById('input')

input.addEventListener('change', async () => {
  try {
    const rows = await readXlsxFile(input.files[0])
    // 跳过表头行,提取所有IMEI值并过滤空值
    const imeiList = rows.slice(1).map(row => row[0]).filter(Boolean)
    // 构建目标JSON结构
    const finalResult = {
      imei: imeiList
    }
    // 输出或使用结果
    console.log(JSON.stringify(finalResult, null, 2))
    // 示例:将结果显示到页面
    document.getElementById('output').textContent = JSON.stringify(finalResult, null, 2)
  } catch (error) {
    console.error('转换失败:', error)
  }
})

代码实现(使用Schema解析,更可靠)

如果你的Excel表头明确(比如表头为"IMEI"),推荐使用read-excel-file的Schema功能精准匹配列,避免列索引变动导致的问题:

import readXlsxFile from 'read-excel-file'

const input = document.getElementById('input')
// 定义Schema,匹配Excel表头
const schema = {
  'IMEI': {
    prop: 'imei',
    type: String
  }
}

input.addEventListener('change', async () => {
  try {
    const { rows } = await readXlsxFile(input.files[0], { schema })
    // 提取所有有效IMEI值
    const imeiList = rows.map(item => item.imei).filter(Boolean)
    // 生成目标结构
    const finalResult = {
      imei: imeiList
    }
    console.log(JSON.stringify(finalResult, null, 2))
  } catch (error) {
    console.error('转换失败:', error)
  }
})

关键说明

  • rows.slice(1):跳过Excel的表头行,确保只处理数据行
  • .filter(Boolean):过滤掉空的IMEI值(比如空行、空单元格),避免数组中出现无效值
  • 若你的IMEI列不在第一列或表头不是"IMEI",只需对应调整列索引或Schema中的表头名称即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:25:21