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

如何将动态字符串数组转换为带自定义命名键的对象?

问题描述

我有如下字符串数组:

let arrayExample = ['', 'test1', 'test2', '', 'test3', 'test1', ''];

该数组是动态的,长度随时可能变化。我希望将其转换为如下格式的对象:

{
    Property0: '',
    Property1: 'test1',
    Property2: 'test2',
    Property3: '',
    Property4: 'test3',
    Property5: 'test1',
    Property6: ''
}

能否动态声明键/属性名?我尝试了以下方法,但生成的是数字键:

newArrayExample = Object.assign({}, arrayExample);
console.log(newArrayExample);
// { 0: '', 1: 'test1', 2: 'test2', 3: '', 4: 'test3', 5: 'test1', 6: '' }

我还尝试了reduce(),但它只返回唯一值,而我需要保留所有值,可能是用法有误:

newArrayExample = arrayExample.reduce((a, v) => ({ ...a, [v]: v}), {});
解决方案

你之前用reduce出错的核心原因是把数组元素的值v当成了对象的键——当数组里出现重复值时,后面的键值对会直接覆盖前面的。要实现需求,应该用数组的索引来生成PropertyX格式的键。

方法1:正确使用reduce

利用reduce回调的第三个参数(当前元素的索引i)构建属性名:

const arrayExample = ['', 'test1', 'test2', '', 'test3', 'test1', ''];
const result = arrayExample.reduce((acc, curr, i) => {
  acc[`Property${i}`] = curr;
  return acc;
}, {});

console.log(result);
// 输出目标格式的对象

方法2:使用forEach遍历

直接遍历数组,逐个给空对象添加对应属性:

const arrayExample = ['', 'test1', 'test2', '', 'test3', 'test1', ''];
const result = {};
arrayExample.forEach((val, index) => {
  result[`Property${index}`] = val;
});

console.log(result);

方法3:使用Object.fromEntries

先把原数组转成[键名, 值]的二维数组,再转换为目标对象:

const arrayExample = ['', 'test1', 'test2', '', 'test3', 'test1', ''];
const result = Object.fromEntries(
  arrayExample.map((val, i) => [`Property${i}`, val])
);

console.log(result);

以上三种方法都能动态生成PropertyX格式的键,完整保留数组所有元素,完全适配动态变化的数组长度。

内容的提问来源于stack exchange,提问作者LOL. NO.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:33:17