无法使用变量来访问字段内的数组成员
问题描述:
为什么我不能使用变量来访问文档中的某些内容?如果我硬编码它的工作领域,但使用一个变量,它不会。无法使用变量来访问字段内的数组成员
building = "AS"
room = "243"
item = "whiteBoard.votes[0]"
RI.findOne({$and: [{"building": building }, {"room": room}]}, (err, x) => {
console.log(x.whiteBoard.votes[0]) //works
console.log(x[item]) //undefined
答
此功能没有在任何地方定义 - 所以它不会工作。你必须拆分访问:
console.log(x["whiteBoard"]["votes"][0])
另外,如果你需要能够使用X.Y
标记访问键,可以拆分对.
串并单独访问这些。
另一种选择是使用lodash
的get
方法:https://lodash.com/docs/4.17.4#get
看到这里https://*.com/questions/5187530/variable-variables-in-javascript –
@BeingSunny是不是真的适用... –