我是javascript/typescript的新手,我在typescript中找到了一种基于如下过滤器类型创建动态命名对象& obj属性的方法
数字类型筛选器属性:
{
"filterType": "",
"type": "",
"filter":'',
"filterTo":''
}
文本类型过滤器属性:
{
"filterType": "",
"type": "",
"filter": ""
}
日期类型筛选器属性:
{
"dateFrom": "",
"dateTo": "",
"filterType": "",
"type": ""
}
基于所选的过滤器类型,我希望创建具有特定过滤器类型属性的对象,如下所示
"filterModel": {
"OriginDate": { <--------------- this column name I will be getting at runtime which i want to be the object name
"dateFrom": "2022-09-21 00:00:00", >
"dateTo": "2022-09-21 00:00:00", >
"filterType": "date", > properties i want to set based on filter type
"type": "inRange" >
},
"Score": { <--------------- this column name I will be getting at runtime which i want to be the object name
"filterType": "number", >
"type": "inRange", >
"filter": 0, > properties i want to set based on filter type
"filterTo": 90 >
},
"Title": { <--------------- this column name I will be getting at runtime which i want to be the object name
"filterType": "text", >
"type": "contains", > properties i want to set based on filter type
"filter": "wire" >
}
}
假设生成此对象所需的输入为
generateFilterModel(columnName : string ,filterType : any ,filtervalues: any[])
{
// logic -> generating the object and adding it to filterModel {}
}
要删除所有过滤器,我将有一个按钮来将filterModel {}设置为空
最终预期输出:
1.对于输入-〉this.generateFilterModel('OriginDate','Date',filtervalues[])
//(列名,过滤器类型,过滤器值)
输出:
"OriginDate": {
"dateFrom": "2022-09-21 00:00:00",
"dateTo": "2022-09-21 00:00:00",
"filterType": "date",
"type": "inRange"
}
1.对于输入-〉this.generateFilterModel('Score','number',filtervalues[])
//(列名,筛选器类型,筛选器值)
输出:
"Score": {
"filterType": "number",
"type": "inRange",
"filter": 0,
"filterTo": 90
}
1.对于输入-〉this.generateFilterModel('Title','text',filtervalues[])
//(列名,过滤器类型,过滤器值)
输出:
"Title": {
"filterType": "text",
"type": "contains",
"filter": "wire"
}
1条答案
按热度按时间kmbjn2e31#
基本方式:
您应该首先定义过滤器的接口:
然后应用于您的函数
在这种情况下,返回类型将变为
Record<string, Filter>
,它很宽,但已经适合大多数用法。一些高级方法:
如果类型需要更正确,如
columnName
必须在类型中已知,则可以是:另外,如果
Filter
的类型必须更精确,则需要先定义一个map:并且函数将是: