i am having trouble sorting a multidimensional object by an embedded key value. i have this object:
var myClients =
{ 'cccc' : { newValue : 'test three'
, timeTest : 3
}
, 'bbbb' : { newValue : 'test two;'
, timeTest : 2
}
, 'aaaa' : { newValue : 'test one'
, timeTest : 1
}
};
console.log(util.inspect(myClients) ) ;
// current object displayed in raw order
for (var key in myClients) {
console.log(key + ' ' + util.inspect(myClients[key]));
}
i am trying to return the array sorted by the "timeTest" value. this was my best guess but it did not work.
tmpArray = _.sortBy(myClients, function(row) { return row.timeTest; } );
console.log(util.inspect(tmpArray));
for ( var result in tmpArray ) {
console.log( (_.invert(myClients))[result] );
}
_.invert is not working for me, and it does not seem very efficient to use it anyways.
the other examples i see are on a single dimensional object.
any suggestions are greatly appreciated.
edit:
this could possibly qualify as an answer since it does just what i want, but it does not seem efficient at all having to loop through the primary object every time:
// display the original object
for (var key in myClients) {
console.log(key + ' ' + util.inspect(myClients[key]));
}
// create a new sorted array
var tmpArray = _.sortBy(myClients, function(key) { return key.timeTest; } );
var sortedClients = {};
for ( var result in tmpArray ) {
for ( var key in myClients ) {
if ( myClients[key] === tmpArray[result] ) {
sortedClients[key] = myClients[key];
break;
}
}
}
// now display the sorted object
for (var key in sortedClients) {
console.log(key + ' ' + util.inspect(myClients[key]));
}
i would think that the underscore (dot)invert function would work but i was unable to apply it.