You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 09:22:55