如何在节点中进行 Json 对象排序.js

how to do Json object Sorting in the node.js

本文关键字:Json 对象 排序 js 节点      更新时间:2023-09-26
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"对数据进行排序

怎么办?

这是我在我的

个人代码中如何做到这一点。如果你还没有使用 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
}