-1

I have some enum objects and i want to get its lebel by it's value.

Let's say this is my enum list

const enumList = {
    businessType: [
        { value: "b", label: "B2B" },
        { value: "s", label: "SAAS" },
        { value: "c", label: "C2C" },
    ],
    userType: [
        { value: "A", label: "Admin" },
        { value: "s", label: "Super User" },
        { value: "t", label: "trainer" },
    ]
}

So now I want to get a particular object label by its key.

like this,

enumList.userType.getLabel('s')'
// super user

I mean, i want to make it re-usable, currently i am doing like this and i dont like it

index = enumList.userType.findIndex(x => x.value ==="s");
enumList.userType[index].label
// super user

Does anyone know how can i make it re-usable to access it from globally like this enumList.userType.getLabel('s) ?

Dan O
  • 6,022
  • 2
  • 32
  • 50

2 Answers2

0

This custom Array method will allow you to do this enumList.userType.getLabel('s') and receive 'Super User'

Array.prototype.getLabel = function(val) {
  return this.find(({value}) => value === val).label
}
Michael Cleary
  • 164
  • 1
  • 4
  • Brother, i need array prototype method to access it globally –  Oct 03 '21 at 21:23
  • edited my answer to use a custom Array method to be used as you specified in the question – Michael Cleary Oct 03 '21 at 21:37
  • the updated one works well, thanks for you help –  Oct 03 '21 at 21:41
  • This is a bad answer. See [Why is extending native objects a bad practice?](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) – Adam Jenkins Oct 03 '21 at 21:41
  • This is the answer being asked for specifically, not necessarily the best way to do it. In comments above, it was clarified that they wanted an Array prototype method. – Michael Cleary Oct 03 '21 at 21:44
  • `This is the answer being asked for specifically` - [XY Problem](https://en.wikipedia.org/wiki/XY_problem) – Adam Jenkins Oct 03 '21 at 22:39
0

See Why is extending native objects a bad practice?

It looks like you want a one-liner, so just use find

const { label } = enumList.userType.find(userType => userType.value === 's');
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100