简体   繁体   中英

TypeScript enum to specific object

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.

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"
    ]
  }
}

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": "" }

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

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM