1

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.

2
  • 1
    Wouldn't that be a set? Commented Dec 11, 2019 at 13:28
  • Enum on the level of TS is a type and a structure, you cannot enumarate over it. But you can create a type and a data with exact fields as enum has type ObjFromEnum = Record<SupportedLanguages, ''> const obj: ObjFromEnum = { [SupportedLanguages.en]: '', [SupportedLanguages.fr]: '', }; Commented Dec 11, 2019 at 13:32

4 Answers 4

3

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"
    ]
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Even simpler: Object.keys(supportedLanguages).reduce((a,k)=>Object.assign(a,{[k]:''}),{})
2

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.