如何按单个整数字段对JSON排序? [英] How to sort JSON by a single integer field?
本文介绍了如何按单个整数字段对JSON排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下JSON:
{
title: 'title',
...,
order: 0
}, {
...,
order: 9
}, {
...,
order: 2
}
... JSON包含许多字段,如何根据 order 字段对它们进行排序?
... the JSON includes many fields, how can I sort them based on the order field?
我一直在寻找内置在nodejs中的东西,但找不到任何可能对这种情况有用的东西.
I was looking for something build into nodejs but I couldn't find anything that might be useful for that case.
推荐答案
首先,您需要有效的JSON,如下所示:
At first, your need valid JSON, like that:
var unsorted = {
"items": [
{
"title": "Book",
"order": 0
},
{
"title": "Movie",
"order": 9
},
{
"title": "Cheese",
"order": 2
}
]
};
之后,您可以轻松地对items
进行排序并将其存储在列表中.
Afterwards you can easily sort the items
and store them in a list.
var sorted = unsorted.items.sort(function(a, b) {return a.order - b.order});
这篇关于如何按单个整数字段对JSON排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文