如何在节点中进行 Json 对象排序.js
how to do Json object Sorting in the node.js
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
}
相关文章:
- jQuery匹配JSON对象的部分文本
- 如何在Javascript中将JSon对象转换为数组
- 我可以在json对象中添加一个函数吗
- 使用JS将数组转换为json对象
- 如何为json对象中的段发送array[]
- 将JSON对象传递给angular指令
- 更改JSON对象的结构
- 访问JSON对象内部的数组元素
- 在ejs-partial中对JSON对象进行迭代
- 遍历 JSON 对象并检查 URL 是否以某个值结尾
- 访问嵌套JSON对象的键,其中键是动态的
- json对象中缺少对象循环
- 发送json对象或使用express路由呈现视图
- 在play2框架中向json对象添加下拉列表项
- 元素名称上带有短划线 (-) 字符的 Json 对象
- autocomplete不接受源的json对象
- 如何在javascript中创建动态json对象
- 在使用客户端脚本时拾取JSON对象
- 如何通过json对象数组为嵌套对象赋值
- 构造JSON对象