Sorting this Object by Name...
var addObjectResponse = [{
'SPO2': '222.00000',
'VitalGroupID': 1152,
'Temperature': 36.6666666666667,
'DateTimeTaken': '/Date(1301494335000-0400)/',
'UserID': 1,
'Height': 182.88,
'UserName': 'Admin',
'BloodPressureDiastolic': 80,
'Weight': 100909.090909091,
'TemperatureMethod': 'Oral',
'Resprate': 111,
'HeartRate': 111,
'BloodPressurePosition': 'Standing',
'VitalSite': 'Popliteal',
'VitalID': 1135,
'Laterality': 'Right',
'HeartRateRegularity':开发者_如何转开发 'Regular',
'HeadCircumference': '',
'BloodPressureSystolic': 120,
'CuffSize': 'XL',
}];
How can i sort this object by name?
I'm assuming here that your addObjectResponse
array contains more than one element, and you wish to sort these elements according to their UserName
property.
First, you need a function that compares names. It returns "0" when the two names are the same, "1" when the second name should be after the first, and "-1" when the second name should be before the first. A bad example would be:
function compare(a,b) {
if (a < b) return 1;
if (a > b) return -1;
return 0;
}
This example is bad because you probably want to sort in a case-insensitive way, or based on last name then first name, but it will work.
Once you have your comparison function, you can use the sort()
member function:
addObjectResponse.sort(function(a,b) { return compare(a.UserName, b.userName) });
Then, your array will be sorted.
ES5 solution, which is available in all 'Major' browsers:
Object.keys( addObjectResponse[0] ).sort().forEach(function( key ) {
console.log( key, ': ', addObjectResponse[0][key] );
});
Since JavaScript guarantees no ordering of object properties (keys) you'll need to maintain your own array of their ordering which you can then iterate to get the corresponding properties in sorted order:
function getSortedKeys(o) {
var ns=[], i;
for (i in o) { ns.push(i); }
return ns.sort();
}
var sortedKeys = getSortedKeys(addObjectResponse[0]);
sortedKeys; // => ["BloodPressureDiastolic", "BloodPressurePosition", "BloodPressureSystolic", "CuffSize", ...
精彩评论