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

时间:2021-02-14 17:49:23

标签: javascript arrays string javascript-objects converters

基本上是从这个['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 个答案:

答案 0 :(得分:4)

使用.reduce

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

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

console.log(res);

答案 1 :(得分:3)

使用 Object.fromEntriesmap 键值对形式:

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

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

console.log(result);