如何将对象数组转换为键名带索引后缀的单个对象?
数组转指定键名格式的单个对象
需求:将对象数组转换为键名格式为{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
相关产品推荐
相关产品推荐

