前端怎么定义字典更好呢

96 天前
 shilianmlxg

我需要一个字典,要有一下三点,并且后期可以扩展字段
key 键名称(下面的 OR,PACU)
value 值(下面的 1,2)
label 值
color 值(可选)

现在定义的两个 一个 enum 一个 map 。觉得有点多余,

问下最优解是什么,

我希望通过访问字段的方式就能知道该字典所对应的值,比如 ROOM_TYPE_ENUM.OR

export const enum ROOM_TYPE_ENUM {

OR = 1, // 手术间

PACU = 2 // 复苏室

}



export const ROOM_TYPE_MAP = [

{

label: '手术间',

value: 1

},

{

label: '复苏室',

value: 2

},

]

3283 次点击
所在节点    程序员
29 条回复
retrocode
95 天前
一种方式是直接按静态类处理, 扩展性更好些. 任意自增方法或属性

```ts
class TsEnum {
public readonly code: string
public readonly name: string
constructor(code: string, name: string) {
this.code = code
this.name = name
}
public static getInstanceByCode<T extends TsEnum>(this: new (code: string, name: string) => T, code: string): T | null {
const enumValues = Object.values(this)
for (const enumValue of enumValues) {
if (enumValue instanceof this && enumValue.code === code) {
return enumValue
}
}
return null
}
}

class SystemEnum extends TsEnum {
public static readonly FOO1 = new SystemEnum('foo1', 'FOO1')
public static readonly FOO2 = new SystemEnum('foo2', 'FOO2')
}

console.log(SystemEnum.getInstanceByCode('foo1'))
console.log(SystemEnum.FOO1.name)

```
yangg
95 天前
之前写过一个

/**
* @param {{ name: string, text: string, code?: number | string }[]} enums
* @returns {[Object, {id: number | string, text: string}[]]}
*/
function createEnum(enums) {
const Enum = {}
const options = []
for (let i = 0; i < enums.length; i++) {
const x = enums[i]
const code = 'code' in x ? x.code : i + 1
Enum[x.name] = code
// Enum[code] = x.text // cannot use Object.values
Object.defineProperty(Enum, code, {
value: x.text,
// implies enumerable: false
})
options.push({id: code, text: x.text})
}
Object.freeze(Enum)
return [Enum, options]
}
yangg
95 天前
使用
export const [ContractType, ContractTypeOptions] = createEnum([
{ name: 'Standard', text: '标准合同', code: 1 },
{ name: 'NonStandard', text: '非标准合同', code: 0 },
])

ContractType.Standard = 2 // ❌ throws a 'Error'.
yangg
95 天前
1. 方便直接从名称取值
2. 同时方便下拉列表显示
Livid
95 天前
@Moonless 请不要再把 AI 生成的回复发到这里。
baoshijiagong
95 天前
AI 回复当然存在问题,按照问题要求,已经用了 OR 作为对象的 key 了,那么不再需要 key 的属性,属于多此一举。AI 没有思考,程序员们解决问题避免用 AI 吧,AI 只是一个程序,可以参考,就像用 Google 一样。

题主的问题也有错误,ROOM_TYPE_MAP 是个 Array ,这个命名牛头不对马嘴。

作为回答,我觉得这样即可:
export const enum ROOM_TYPE_ENUM {
OR = {
{
label: '手术间',
value: 1
},
},

PACU = {
label: '复苏室',
value: 2
},
}

value 都可以不需要,可以选加 color ,可以加 order ,来为下拉框排序
baoshijiagong
95 天前
补充:value 应该是传给后端的,还是需要。
wzdsfl
94 天前
@w568w 你是不是魔怔了,这也要 @ 让他永 ban ?
Moonless
94 天前
@Livid Sorry, 后续不会了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1053856

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX