简体   繁体   English

无法使用Object.keys()在数组中获取JSON密钥

[英]Unable to get JSON keys in an array using Object.keys()

I'm trying to retrieve all the keys off a query result into an array. 我正在尝试将查询结果中的所有键检索到数组中。 Should be a super easy thing to do but somehow am not able to. 应该是一个非常容易的事情,但不知何故我无法做到。 Here's the snippet: 这是片段:

fromMongoDB = parent.posts[0]
returnedkeys = Object.keys(fromMongoDB);
console.log(fromMongoDB);
console.log('-----------------------------');
console.log(returnedkeys);

The data I'm receiving into fromMongoDB is an object with two key-value pairs: 我从fromMongoDB接收的数据是一个具有两个键值对的对象:

{
   id: <some ID>,
   title: <some title>
}

Using Object.keys() , I intend to get an array of the two keys: 使用Object.keys() ,我打算获得两个键的数组:

[
  id, title
]

But this is what I'm getting instead: 但这就是我所得到的:

{ id: '5ba1f3e7cc546723422e62a4', title: 'A Title!' }
-----------------------------
[ '__parentArray',
  '__parent',
  '__index',
  '$__',
  'isNew',
  'errors',
  '_doc',
  '$init' ]

What am I doing wrong? 我究竟做错了什么? Is fromMongoDB not a JSON object? fromMongoDB不是JSON对象吗?

You can try below aggregation in mongodb 3.4.4 and above 您可以在mongodb 3.4.4及更高版本中尝试以下聚合

db.collection.aggregate([
  { "$project": {
    "keys": {
      "$objectToArray": "$$ROOT"
    }
  }},
  { "$project": { "keys": "$keys.k" }}
])

尝试这样的事情:

Object.getOwnPropertyNames(fromMongoDB);

Try lean() function instead. 尝试使用lean()函数。 Append .lean() to your query and then use Object.keys() to get an array of keys. 将.lean()附加到查询中,然后使用Object.keys()获取键数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM