React中扩展数组通用方法实现按value获取枚举项对应label
实现方案
方案1:封装枚举构造工具(推荐,无全局污染)
该方案不会修改原生JS的内置原型,不会引发全局命名冲突,可维护性和复用性都更高。
首先定义通用枚举构造工具:
// 工具方法全局定义一次即可使用 function createEnum(arr) { // 给当前枚举数组挂载专属方法 arr.getLabel = function(value) { const matchItem = this.find(item => item.value === value) // 匹配不到时默认返回传入的value,也可根据需求改成返回空字符串/其他兜底值 return matchItem ? matchItem.label : value } // 后续如果需要扩展其他能力(比如根据label查value、获取所有枚举值列表等),可以直接在这里新增挂载 return arr }
改造你的枚举列表定义:
const enumList = { businessType: createEnum([ { value: "b", label: "B2B" }, { value: "s", label: "SAAS" }, { value: "c", label: "C2C" }, ]), userType: createEnum([ { value: "A", label: "Admin" }, { value: "s", label: "Super User" }, { value: "t", label: "trainer" }, ]) }
调用效果完全符合需求:
enumList.userType.getLabel('s') // 输出结果为 Super User
方案2:扩展Array原型(仅适合小型无冲突场景)
如果需要所有符合[{value, label}, ...]结构的数组都可以直接调用该方法,可以全局扩展Array原型:
// 全局只需执行一次 Array.prototype.getLabel = function(value) { const matchItem = this.find(item => item?.value === value) return matchItem ? matchItem.label : value }
直接调用即可:
enumList.userType.getLabel('s') // 输出结果为 Super User
注意:该方案会修改原生数组的原型,大型项目/多依赖共存场景下可能引发命名冲突,非特殊情况不建议使用。
内容的提问来源于stack exchange,提问作者user16718966
相关产品推荐
相关产品推荐

