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

Viewed 49

Basically, is from this ['padding', 'children', 'className'] to this:

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

I had tried a few methods as follows:

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

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

Output:

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

But the collections are like "independents" inside the array... Please, help me!

2 Answers

Use .reduce:

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

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

console.log(res);

Use Object.fromEntries and map it to key value pair form:

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

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

console.log(result);

Related