Today, I need to sort the JSON by its key(properties) and I write the following extended function to array element.
Array.prototype.extendSort = function(field,desc){
function sortField(a,b){
if (a[field] == b[field]){
return 0;
}
var result = a[field] > b[field]?1:-1;
if (desc == true) result=result*-1;
return result;
}
this.sort(sortField);
}
var testjson = [{"id":3, "name":"Charlie"},{"id":5, "name":"Danny"},{"id":4, "name":"Billy"}]
testjson.extendSort("id", false);
PS:
If you want to loop through the array using for...in statement, you may find that the extendSort also recognizes as one of the object.
You should use the following code to deal with that:
for (name in testjson) {
if (testjsonj.hasOwnProperty(name)) {
...
}
}
Sunday, August 30, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment