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

TypeScript如何将平面数组按前N项为键转换为对象数组

TypeScript 平面数组转对象数组通用实现

完整通用函数实现

function flatArrayToObjectArray(flatArr: string[], chunkSize: number): Record<string, string>[] {
    // 数组分块逻辑
    const chunks = flatArr.reduce((resultArray, item, index) => { 
        const chunkIndex = Math.floor(index / chunkSize)
        if(!resultArray[chunkIndex]) {
            resultArray[chunkIndex] = []
        }
        resultArray[chunkIndex].push(item)
        return resultArray
    }, [] as string[][])

    // 边界兼容:数组长度不足时直接返回空
    if (chunks.length < 2) return []

    // 取第一块作为键集合
    const keys = chunks[0]
    // 剩余分块映射为对象数组
    return chunks.slice(1).map(dataChunk => {
        return dataChunk.reduce((obj, value, index) => {
            // 仅处理键长度范围内的数据,忽略多余项
            if (index < keys.length) {
                obj[keys[index]] = value
            }
            return obj
        }, {} as Record<string, string>)
    })
}

使用示例

let testArr = ["id", "ser", "add", "1", "asd", "82.255", "2", "ert", "82.119", "3", "pol", "82.250"];
let newArr = flatArrayToObjectArray(testArr, 3);
console.log(newArr);

执行后输出的newArr和你预期的结构完全一致。

特性说明

  • 支持任意合法长度的平面数组输入
  • 支持自定义分块长度,自动适配键的数量
  • 自动兼容数组长度不足、数据块长度超过键长度等异常场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 11:15:04