根据属性值对 JSON 数组进行排序
Posted
技术标签:
【中文标题】根据属性值对 JSON 数组进行排序【英文标题】:Sort JSON array based on its attributes value 【发布时间】:2014-08-21 14:17:42 【问题描述】:这是我得到的 JSON 数组:
[
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
,
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
,
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
]
但我需要按“年龄”属性对这个 JSON 数组 desc 进行排序。 我想要的 JSON 数组应该如下所示:
[
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
,
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
,
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
]
如何做到这一点?
【问题讨论】:
【参考方案1】:试试这个:
var arr = [
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
,
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
,
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
]
var prop = "Age"
arr.sort(function(a,b)
var cmp = -1
if (a.hasOwnProperty(prop) && b.hasOwnProperty(prop))
var a_prop_value = parseFloat(a[prop])
var b_prop_value = parseFloat(b[prop])
if (isNaN(a_prop_value) || isNaN(b_prop_value))
//string comp
cmp = a[prop].localeCompare(b[prop])
else
cmp = a_prop_value - b_prop_value > 0? 1 : a_prop_value - b_prop_value ==0? 0:-1
return cmp;
);
【讨论】:
请注意,localeCompare 取决于实现,可能不会产生一致的结果。 它在我们查找 Name 时给出了正确的数组结构,但没有给出 Age 属性的正确解。 我读错了,你是 wright @thevan,看看我上次的编辑 好的,现在你可以按任何 JSON 属性排序,只需要更改属性变量【参考方案2】:天真的答案是使用 Array.prototype.sort([compareFunction])。妨碍:
function compareAgeProperty(a,b)
return (parseInt(a.Age) < parseInt(b.Age)) ? -1 : 1;
var arr = [/* your array's data here */];
arr.sort(compareAgeProperty);
我建议你看看: https://developer.mozilla.org/en/docs/Web/javascript/Reference/Global_Objects/Array/sort
您的 Age 属性是一个字符串,因此作为字符串进行比较,意思是 '80'
【讨论】:
是的..当我将 符号时,它提供了所需的解决方案。谢谢..【参考方案3】:var a = [
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
,
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
,
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
];
a.sort(function(x,y)return y["Age"]-x["Age"]);
console.log(a);
【讨论】:
【参考方案4】:使用以下泛型函数 predicateBy 按所需字段对数据进行排序
var data=[
"Name" : "Sachin",
"Age" : "41",
"Team" : "Mumbai"
,
"Name" : "Dravid",
"Age" : "42",
"Team" : "Rajasthan"
,
"Name" : "Yuvraj",
"Age" : "31",
"Team" : "Bangalore"
]
function predicatBy(prop)
return function(a,b)
if( a[prop] > b[prop])
return 1;
else if( a[prop] < b[prop] )
return -1;
return 0;
//Usage
data.sort( predicatBy("age") );
console.log(data);
【讨论】:
更好的名称是 sortBy,因为谓词是传递的属性名称。 ;-)【参考方案5】:var _ = require('underscore');
var data = ...your data...
console.log(_.sortBy(data, 'Age').reverse());
【讨论】:
以上是关于根据属性值对 JSON 数组进行排序的主要内容,如果未能解决你的问题,请参考以下文章