Reputation: 5631
I have the following TypeScript enum:
export declare enum SupportedLanguages {
en,
fr
}
If I import it in my react application and console.log
it, I will get the following object returned:
{
en: "en",
fr: "fr"
}
How can I manipulate it, so that I get the following object returned?
{
en: "",
fr: ""
}
I tried it with const Lang = Object.keys(SupportedLanguages)
and also with .map()
but I did not get the expected object returned.
Upvotes: 1
Views: 553
Reputation: 191986
You can get the keys, and map them to a tupple of [key, '']
, and convert back to an object with Object.fromEntries()
:
const supportedLanguages = {
en: "en",
fr: "fr"
};
const result = Object.fromEntries(
Object.keys(supportedLanguages)
.map(k => [k, ''])
);
console.log(result);
If you receive an error like this:
TS2550: Property 'fromEntries' does not exist on type 'ObjectConstructor'. Do you need to change your target library? Try changing the
lib
compiler option to 'es2019' or later.
Add es2019
to compilerOptions.lib
in your project's tsconfig.json
:
{
"compilerOptions": {
"lib": [
"es2019"
]
}
}
Upvotes: 3
Reputation: 48630
You could translate the object to a key arr → set → map.
Here are some trivial translation functions:
const keySet = o => new Set(Object.keys(o))
const arrToMap = a => a.reduce((a, k) => Object.assign(a, { [k]: '' }), {})
const setToMap = s => arrToMap([...s])
const keyMap = o => setToMap(keySet(o))
const SupportedLanguages = {
en : "en",
fr : "fr"
}
console.log(Object.keys(SupportedLanguages)) // arr
console.log([...keySet(SupportedLanguages)]) // set
console.log(keyMap(SupportedLanguages)) // obj
.as-console-wrapper { top: 0; max-height: 100% !important; }
Upvotes: 1
Reputation: 908
In typescript
I am using below solution,
export declare enum SupportedLanguages {
en="",
fr=""
}
Also you can use lib. for some default methods. https://www.npmjs.com/package/enum-values
Upvotes: 2
Reputation: 28750
Are you just looking to get a new object with all the data as empty strings?
var supportedLanguages = {
en: "en",
fr: "fr"
};
var result = Object.keys(supportedLanguages)
.reduce((accum, key) =>
Object.assign(accum, { [key]: "" })
, {});
console.log(result); // { "en": "", "fr": "" }
Upvotes: 2