Cuberic Cuberic - 6 days ago 5
Javascript Question

sortBy keeping key name

I'm trying to sort an object but can't seem to keep the key name of each object after sorting.

Here is the sample json I'm sorting on

series_data: {
embeded: {
objectNameA: {
item: {
last:{reportdate:2014-10-05, trend:=, change:0, value:0},…},
first: {reportdate:2013-01-06, trend:?, change:null, value:0},
high: 1,
low: 0,
median: 0.043478260869565216,
series: [{reportdate:2013-01-06, trend:?, change:null, value:0},…]
},
objectNameB: {…}


I need the objectName becasue it's used in my templates to describe everything else.

here is how I am sorting the data

var items = _.sortBy(series_data.embeded, function(series, index) {
return series.cd.last.value
}).reverse();`


This returns
0:{…}, 1:{…}, 2:{…}
, when I need it to be
objectNameA:{…},objectNameB:{…}
.

OR better yet

0:{objectNameA:{…},…}, 1:{objectNameB:{…},…}


How do I keep or add the objectName while sorting in order from highest to lowest?

Answer

I don't think that you can do this with a single call to _.sortBy().

However, you can accomplish it in two steps:

  1. call _.sortBy() and assign the key of each object as a property
  2. call _.each() on the sorted array to get the desired object structure

Here is an example JSBIN

The underlying problem is that objects are unordered collections of properties.

Comments