Home > database >  react adding new array method to return array's object item by it's key
react adding new array method to return array's object item by it's key

Time:10-04

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) ?

CodePudding user response:

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
}

CodePudding user response:

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');
  • Related