有没有方法将字符串数组转换成对象集合?

3

基本上,是从这个 ['padding', 'children', 'className'] 转化为这样:

{
    padding: "padding",
    children: "children",
    className: "className",
}

我尝试过以下几种方法:

const arr = ['padding', 'children', 'className'];

const obj = Object.keys(arr).map((prop) => ({ [prop]: prop }))`;

输出结果:

[{padding: "padding"}, {children: "children"}, {className: "className"}]

但是集合就像数组内的“独立”元素... 请帮助我!
2个回答

4
使用 .reduce() 方法:

const arr = ['padding', 'children', 'className'];

const res = arr.reduce((acc,item) => {
  acc[item] = item; return acc;
}, {});

console.log(res);


请问您能否解释一下它是如何工作的?谢谢! - soujvnunes
基本上这是一种迭代数组的技巧,其中“acc”最初设置为空对象“{}”以进行更新。在每次迭代中,我们使用索引处的元素(在这种情况下为“item”)向对象添加一个新的键值对。最终,输出将是每个唯一项的映射作为“key”和“value”。我添加了有关更多详细信息的文档参考。 - Majed Badawi
使用 reduce()Object.fromEntries() 有什么区别?是否有“推荐”的方法? - soujvnunes
1
@JoãoVictor 两种方法都可以实现这个任务,但使用 Object.fromEntries 方法需要先遍历数组并创建键值对,在传递给函数之前。然而,使用 .reduce 方法可以在一个迭代中节省时间,更加直观简洁。 - Majed Badawi

3
使用 Object.fromEntries 并将其映射为键值对形式:

const arr = ['padding', 'children', 'className'];

const result = Object.fromEntries(arr.map(k=>[k,k]));

console.log(result);


1
谢谢!我猜这比使用 reduce() 更简单的解决方案... - soujvnunes
只是为了好玩:你可以滥用 Set 来为你做映射 const obj = Object.fromEntries(new Set(arr).entries()); 但请注意,这不是一个严肃的建议。不要在生产环境中这样做。至少要有10行注释来解释这里发生了什么以及为什么选择这种方式。 - Thomas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接