I'am getting an array of strings from the server (available image sizes), and I'd like to generate an object out of that array, like this:
[el1,el2...] = { el1:'el1',el2:'el2'...}
So this way when I'am trying to access some value I can see an actual values in the code instead of using indexes. But I don't know what elements my array will consist of, so is there a way of defining types dynamically or maybe another way to achieve the same result?
CodePudding user response:
It sounds like you're asking how to transform an array of strings into an object whose key-value pairs correspond to each value in the array. You can do that with a function like this:
function asObject (strings: string[]): Record<string, string> {
const result: Record<string, string> = {};
for (const str of strings) result[str] = str;
return result;
}
const array = ['el1', 'el2'];
const obj = asObject(array);
console.log(obj); //=> { el1: "el1", el2: "el2" }