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

如何将数组转换为含统一key“libelle”的多对象结构

将数组转换为含指定子对象的结构

针对数组 ["a","b","c","d"],以下几种方法可将其转换为每个键对应包含libelle属性的子对象结构:

方法1:使用Array.prototype.reduce

通过累加器逐步构建目标对象,是这类转换场景的常用方案:

const arr = ["a","b","c","d"];
const result = arr.reduce((acc, item, index) => {
  acc[index] = { libelle: item };
  return acc;
}, {});

console.log(result);

输出结果:

{
  0: { libelle: "a" },
  1: { libelle: "b" },
  2: { libelle: "c" },
  3: { libelle: "d" }
}

方法2:使用Object.fromEntries

利用ES2019引入的API,先将数组映射为键值对数组,再生成目标对象:

const arr = ["a","b","c","d"];
const result = Object.fromEntries(
  arr.map((item, index) => [index, { libelle: item }])
);

console.log(result);

方法3:普通for循环

若需兼容旧运行环境,普通循环是最稳妥的实现方式:

const arr = ["a","b","c","d"];
const result = {};

for (let i = 0; i < arr.length; i++) {
  result[i] = { libelle: arr[i] };
}

console.log(result);

以上三种方法均可生成你需要的结构,避免了直接将数组值作为对象属性值的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:36:21