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

如何在JavaScript中无需指定键名展平嵌套数组键值对

自动扁平化含数组值的对象数组(无需指定键名)

给定输入数组:

[
    { force_x: [1, 2, 3], force_y: [0.3, 0.4, 0.5] },
    { force_x: [4, 5, 6], force_y: [0.0, 0.0, 0.0] },
    { motion_x: [0.7, 0.7, 0.7] }
]

需要将其转换为如下格式的数组,且无需手动指定任何键名:

[
    { force_x: 1, force_y: 0.3 },
    { force_x: 2, force_y: 0.4 },
    { force_x: 3, force_y: 0.5 },
    { force_x: 4, force_y: 0.0 },
    { force_x: 5, force_y: 0.0 },
    { force_x: 6, force_y: 0.0 },
    { motion_x: 0.7 },
    { motion_x: 0.7 },
    { motion_x: 0.7 }
]

解决方案代码

const input = [
    { force_x: [1, 2, 3], force_y: [0.3, 0.4, 0.5] },
    { force_x: [4, 5, 6], force_y: [0.0, 0.0, 0.0] },
    { motion_x: [0.7, 0.7, 0.7] }
];

const output = input.flatMap(obj => {
    // 获取当前对象的所有键值对
    const keyValuePairs = Object.entries(obj);
    // 确定要生成的对象数量(取第一个数组的长度,假设当前对象内所有数组长度一致)
    const itemCount = keyValuePairs[0][1].length;
    // 遍历每个索引,组装对应位置的键值对对象
    return Array.from({ length: itemCount }, (_, index) => {
        return keyValuePairs.reduce((result, [key, arr]) => {
            result[key] = arr[index];
            return result;
        }, {});
    });
});

console.log(output);

代码说明

  • 用flatMap遍历原数组的每个对象,同时将处理后的结果直接扁平化
  • Object.entries(obj)自动获取对象的所有键名和对应数组,无需手动指定
  • 假设单个对象内的所有数组长度一致,若存在长度差异,可根据需求调整(比如取最长数组长度补值,或取最短长度截断)
  • 通过Array.from生成对应数量的空对象模板,再用reduce把每个索引位置的键值对组装成目标对象

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:50:30