【问题标题】:how to do Json object Sorting in the node.js如何在 node.js 中进行 Json 对象排序
【发布时间】:2015-05-11 08:38:41
【问题描述】:
var data={ '0':
   { 
     benchmark: null,
     hint: '',
     _id: '54fe44dadf0632654a000fbd',
     date: '2015-05-10T01:11:54.479Z' },
  '1':
  { 
     benchmark: null,
     hint: '',
     _id: '54fe44d9df0632654a000fac',
     date: '2015-05-10T01:11:53.608Z' },
  '2':
   { 
     body: '{}',
     benchmark: null,
     _id: '54fe44d8df0632654a000fa4',
     date: '2015-05-10T01:11:52.934Z' }
}

// data sorting
console.info(data);

我想按 '_id' 对数据进行排序

怎么做?

【问题讨论】:

  • 你的意思是对变量中的数据进行排序还是对数据库中已有的数据进行排序?
  • _id mongodb objectid,这是时间戳。我想整理一下。在 node.js 中
  • 好吧,你这里似乎没有数组,你有一个包含一系列其他对象的对象。您要么必须转换为对象数组并对数组进行排序,要么编写自己的排序算法。
  • 另外,_id 不是时间戳,您可以使用getTimestamp() 查看_id 的创建时间,但不保证它们是按顺序排列的。来自docs.mongodb.org/manual/reference/object-id : "•对存储 ObjectId 值的 _id 字段进行排序大致相当于按创建时间排序"
  • 好吧,我只想按_id排序。我合并集合的文档。但是,它正在排序,我将按 '_id' 对其进行排序

标签: javascript json node.js mongodb


【解决方案1】:

这是我在个人代码中的做法。如果您还没有使用 Ecmascript 6,您可能需要重新编写 => 函数。

我没有提供比较功能,但您可以使用 [a, b].sort(); 拼凑一个。如果你想要最大程度的简洁。

var data = { '0':
   {
     benchmark: null,
     hint: '',
     _id: '54fe44dadf0632654a000fbd',
     date: '2015-05-10T01:11:54.479Z' },
  '1':
  {
     benchmark: null,
     hint: '',
     _id: '54fe44d9df0632654a000fac',
     date: '2015-05-10T01:11:53.608Z' },
  '2':
   {
     body: '{}',
     benchmark: null,
     _id: '54fe44d8df0632654a000fa4',
     date: '2015-05-10T01:11:52.934Z' }
}

// use functional chaining to create a sorted out of the data
// 1. Object.keys(data) returns an array of the keys in `data`, ie ['0', '1', '2']
// see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
const sorted = Object.keys(data).map((key) => {
  // 2. transform each key to be that value instead.
  //    '1' becomes { benchmark: null, ...}, so now we have an array of values
  //    the end result of map() is  [ { benchmark: null, ... }, ... ]
  //    see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
  return data[key];
}, []).sort((a, b) => {
  // 3. sort the resulting values array using Array.prototype.sort, which allows
  //    you to provide your own comparison callback to determine order.
  return compare(a._id,  b._id);
})

function compare(a, b) {
  // your string ordering code here.
  // feel free to use Array.sort() here to do unicode codepoint order sort.
  // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
}

【讨论】:

  • ``` const sorted = Object.keys(data).reduce((accum, key) => { accum.push(data[key]); return accum; }, [])。 sort((a, b) => { return compare(a._id, b._id); }) ``` 我看不懂这段代码。 ```
  • @Seung 将其更新为更具可读性,并添加了内联 cmets。
猜你喜欢
  • 1970-01-01
  • 2018-02-18
  • 2013-07-08
  • 2018-10-31
  • 1970-01-01
  • 2014-02-22
  • 2011-05-12
  • 2013-07-15
  • 2020-03-06
相关资源
最近更新 更多