代码之家  ›  专栏  ›  技术社区  ›  tom smith

无法使用变量访问字段内的数组成员

  •  0
  • tom smith  · 技术社区  · 8 年前

    为什么我不能使用变量访问文档中的内容?如果我硬编码字段,它会工作,但使用变量则不会。

    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
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Derek Brown Onga Leo-Yoda Vellem    8 年前

    console.log(x["whiteBoard"]["votes"][0])
    

    X.Y 符号,您可以在 . 并分别访问这些。

    另一种选择是使用 lodash get https://lodash.com/docs/4.17.4#get