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

如何将对象数组转换为键名带索引后缀的单个对象?

数组转指定键名格式的单个对象

需求:将对象数组转换为键名格式为{key}{index}的单个对象,索引从1开始(如data1、quantity1),示例如下:

输入示例

const input = [
    {
        data: 'Abc',
        quantity: '1'
    },
    {
        data: 'Def',
        quantity: '2'
    }
];

输出示例

const output = { data1: 'Abc', quantity1: 1, data2: 'Def', quantity2: 2 }

实现代码

const input = [
    {
        data: 'Abc',
        quantity: '1'
    },
    {
        data: 'Def',
        quantity: '2'
    }
];

const output = input.reduce((acc, item, index) => {
    const idx = index + 1;
    Object.keys(item).forEach(key => {
        // 针对quantity字段做字符串转数字处理,其他字段直接赋值
        acc[`${key}${idx}`] = key === 'quantity' ? Number(item[key]) : item[key];
    });
    return acc;
}, {});

console.log(output);

代码说明

  • 使用Array.reduce遍历数组,初始化空对象作为结果容器
  • 数组索引从0开始,所以加1得到示例中的1、2后缀
  • 遍历每个对象的键名,拼接成键名+索引的新键
  • 对quantity字段做类型转换,匹配示例中的数字类型;若不需要类型转换,可直接赋值acc[${key}${idx}] = item[key]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 09:48:28