Search code examples
javascriptarraysstringjavascript-objectsconverters

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


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!


Solution

  • Use .reduce:

    const arr = ['padding', 'children', 'className'];
    
    const res = arr.reduce((acc,item) => {
      acc[item] = item; return acc;
    }, {});
    
    console.log(res);