如何将数组转换为含统一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
相关产品推荐
相关产品推荐

