Home > Software engineering >  Enum of strings into array of objects
Enum of strings into array of objects

Time:03-04

I have an enum I need to create an array of select options of but it isn't as simple when the value isn't a number. The following does not work because

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof MaterialSupportType'.

enum MaterialSupportType {
  Equipment = 'equipment',
  Food = 'food'
}

const materialSupportTypes = Object.keys(MaterialSupportType).map(key => ({
  value: MaterialSupportType[key], name: key
}));

It's probably an easy question but tricky for me.

CodePudding user response:

I think you should use reduce function in order to accumulate data to the end.

enum MaterialSupportType {
  Equipment = 'equipment',
  Food = 'food'
};

const materialSupportTypes = Object.entries(MaterialSupportType).reduce((k, v) => {
    const [key, value] = v;
  return {...k,  ...{[key]: value}};
}, {});

CodePudding user response:

I think this is what you're looking for: use Object.values() instead of Object.keys(), and transform the value as you see fit:

TS Playground

enum MaterialSupportType {
  Equipment = 'Equipment',
  Food = 'Food'
};

const materialSupportTypes = Object.values(MaterialSupportType).map(str => ({
  name: str,
  value: str.toLowerCase(),
}));


console.log(materialSupportTypes);

// [
//   {
//     "name": "Equipment",
//     "value": "equipment"
//   },
//   {
//     "name": "Food",
//     "value": "food"
//   },
// ]

See also: Why does Object.keys() return string[] in TypeScript?


Alternatively (if you're okay with using a type assertion), you can do this:

TS Playground

enum MaterialSupportType {
  Equipment = 'equipment',
  Food = 'food'
};

const materialSupportTypes = (Object.keys(MaterialSupportType) as (keyof typeof MaterialSupportType)[]).map(key => ({
  name: key,
  value: MaterialSupportType[key],
}));


console.log(materialSupportTypes);

// [
//   {
//     "name": "Equipment",
//     "value": "equipment"
//   },
//   {
//     "name": "Food",
//     "value": "food"
//   },
// ]

  • Related