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

Is there a way to turn an array of strings into object collection?

基本上就是从这个['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"}]

但是集合就像数组中的“独立对象”...请帮帮我!

使用.reduce:

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

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

console.log(res);

使用Object.fromEntriesmap它的键值对形式:

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

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

console.log(result);