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

如何遍历类实例对象集合 筛选返回指定属性子集

核心错误原因

  • Array.prototype.map是数组专属方法,你定义的fields是普通对象,没有内置map方法
  • fields中存储的是Checkbox类本身,不是类的实例,无法直接调用实例方法onlySome

最优实现方案

如果你的需求是遍历对象的所有键值对,保留原有键名,值替换为实例调用onlySome的返回结果,实现代码如下:

class Checkbox {
    constructor() {
        this.test1 = 'dsdas';
        this.test2 = 'dsdas';
        this.test3 = 'dsdas';
        this.test4 = 'dsdas';
    }
    onlySome() {
        return {
            test3: this.test3 || null,
            test4: this.test4 || null,
        }
    }
}

const fields = {
    class1: Checkbox,
    class2: Checkbox,
    class3: Checkbox,
    class4: Checkbox,
}

// 遍历对象生成新对象
const filtered = Object.fromEntries(
  Object.entries(fields).map(([key, Clazz]) => {
    // 先实例化类,再调用onlySome方法
    const instance = new Clazz();
    return [key, instance.onlySome()]
  })
)

运行后filtered的输出结构完全符合你的预期:

{
  class1: { test3: 'dsdas', test4: 'dsdas' },
  class2: { test3: 'dsdas', test4: 'dsdas' },
  class3: { test3: 'dsdas', test4: 'dsdas' },
  class4: { test3: 'dsdas', test4: 'dsdas' }
}

特殊场景调整

  • 如果你fields中存储的已经是Checkbox的实例,只需要去掉实例化步骤即可:
// 假设fields是已实例化的对象集合
const fields = {
  class1: new Checkbox(),
  class2: new Checkbox(),
  class3: new Checkbox(),
  class4: new Checkbox(),
}

const filtered = Object.fromEntries(
  Object.entries(fields).map(([key, instance]) => [key, instance.onlySome()])
)
  • 如果需要兼容不支持Object.fromEntries的旧环境,可以用reduce实现相同效果:
const filtered = Object.keys(fields).reduce((result, key) => {
  const instance = new fields[key]();
  result[key] = instance.onlySome();
  return result;
}, {})

内容的提问来源于stack exchange,提问作者Martyn Ball

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:48:03