【问题标题】:How to get an element from a JSON object based on their position in the object?如何根据对象在对象中的位置从 JSON 对象中获取元素?
【发布时间】:2014-12-17 01:58:33
【问题描述】:

我的 mongodb 数据库中有一个对象:

{ _id: 5490dcbacc08e6c1c37752b1,

    Java: { posts: [] },

    Idde: { posts: [] },

    Node: { posts: [] } 

}  

我想访问第二个对象,第三个和第四个。 假设我想在我的 js 代码中获取它们并将它们发送到 Jade 以显示它们。

所以我的路由文件是这样的:

db.categories.find({}, function(err,category ){
        if(err)
        {
            console.error(err);
        }
    else{
        // My code should be here and create an object 
        res.render('follow', {title: 'Follow post', categories:**Here I should insert the category object**});
        }
    }

【问题讨论】:

  • 对象键中没有顺序,所以“对象的第三个元素”是没有意义的。
  • @AlexeyTen 那么如何访问 Java、Idde 和 Node 数组呢?
  • '这里我应该插入类别对象'应该是什么?

标签: json node.js mongodb pug


【解决方案1】:

首先,.find 返回一个集合。要获取单个类别,您需要使用.findOne,或者遍历.find 返回的集合。

其次,这不是“JSON 对象”,这只是一个对象,您可以使用普通的点表示法访问它:category.Javacategory.Node 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多