John Cooper
John Cooper

Reputation: 7641

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?

Upvotes: 1

Views: 88

Answers (3)

Victor Nicollet
Victor Nicollet

Reputation: 24577

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.

Upvotes: 1

maerics
maerics

Reputation: 156444

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", ...

Upvotes: 0

jAndy
jAndy

Reputation: 236032

ES5 solution, which is available in all 'Major' browsers:

Object.keys( addObjectResponse[0] ).sort().forEach(function( key ) {
    console.log( key, ': ', addObjectResponse[0][key] );
});

Upvotes: 0

Related Questions