反应添加新数组方法以按其键返回数组的对象项



我有一些枚举对象,我想通过它的值来获得它的级别。

假设这是我的enum列表

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

现在我想通过键得到一个特定的对象label

,

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

我的意思是,我想让它可重用,目前我这样做,我不喜欢它

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

有谁知道我怎么能使它可重用,从全局访问它像这个enumList.userType.getLabel('s)吗?

这个自定义数组方法将允许您执行此enumList.userType.getLabel('s')并接收'Super User'

Array.prototype.getLabel = function(val) {
return this.find(({value}) => value === val).label
}

明白为什么扩展本地对象是不好的做法吗?

看起来您需要一行代码,所以只需使用find

const { label } = enumList.userType.find(userType => userType.value === 's');

最新更新