如何使用变量作为字段键获取Meteor集合字段值

Hak*_*kki 2 javascript mongodb node.js meteor

我将给出一个代码示例来描述我的问题:

var id = Collection.insert({
    name: 'Charles Darwin',
    likes: 1
});

var someVariable = 'name';

Collection.findOne(id).name // This returns 'Charles Darwin', but how do I use someVariable to get the same result?
Collection.findOne(id).someVariable // This will certainly not work, but what is the right way to do it?
Run Code Online (Sandbox Code Playgroud)

chr*_*dam 5

尝试使用括号表示法访问object属性:

Collection.findOne(id)[someVariable];
Run Code Online (Sandbox Code Playgroud)

  • [关于它的Moar数据.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors) (2认同)