如何使属性动态化(在执行代码之前未知)

How do I make a property dynamic (unknown until the code is executed)?

本文关键字:代码 未知 执行 何使 属性 动态化      更新时间:2023-09-26

这是我处理的数据格式:

ChecksCollection = new Mongo.Collection(null);
ChecksCollection.insert({
  oddsChecked: ['', ''],
  oddsAverages: ['', ''],
  oddsCompeting: ['', ''], 
  ...

dynamic属性可以是"赔率检查","赔率平均","赔率竞争"等。这取决于执行时间。如何使下面的代码工作?

var odds = ChecksCollection.findOne().dynamicProperty[index];

您可以使用 transform 选项创建具有 Object.defineProperty 的 getter :

ChecksCollection.findOne({}, {
  transform: doc => Object.defineProperty(doc, 'dynamicProperty', {
    get: function getDynamicProperty() {
      // Your logic here
      // This should return a value (unless you want some obscure
      // side-effecting getter, which no you don't)
      if (this.something) {
        return 42;
      }
      else {
        return 53;
      }
    }
  })
);

只要不使用箭头函数(锁定this),您就可以使用 this 访问 getter 所在的对象。

试试template string

var t = ['oddsChecked', 'oddsAverages', 'oddsCompeting'];
var s = t[i]; // the `i` determined at the running time.
var odds = ChecksCollection.findOne({`${s}`: value})...;