如何在TypeScript中动态设置对象元素?替换setFilterModel的键名
Solution: Use ES6 Computed Property Names
Got it, this is exactly what ES6's computed property names were made for! You can dynamically use the value of filterForElement as the object key by wrapping it in square brackets [].
Modified Code
Here's how your updated component snippet will look:
filterForElement: string; constructor(private api: someApiService) { } someInitFunction(params: any) { this.filterForElement = params.filterForElement; // 组件初始化后该值可用 } onChangeDrop() { // Use computed property name to replace 'state' with filterForElement's value this.api.setFilterModel({ [this.filterForElement]: { filterType: "text", type: "equals", filter: valueToUse // Make sure this variable is available in the current scope } }); }
How It Works
Computed property names let you use variables or expressions as object keys directly. When onChangeDrop runs, JavaScript will evaluate this.filterForElement and use its current value as the key in the object passed to setFilterModel—exactly what you need.
Optional Guard Clause
To avoid unexpected behavior if filterForElement hasn't been initialized yet (e.g., someInitFunction didn't run), you can add a quick check:
onChangeDrop() { if (!this.filterForElement) { console.warn("filterForElement hasn't been initialized yet!"); return; } this.api.setFilterModel({ [this.filterForElement]: { filterType: "text", type: "equals", filter: valueToUse } }); }
内容的提问来源于stack exchange,提问作者Sourav Raj
相关产品推荐
相关产品推荐

