Cuberic Cuberic - 2 months ago 25
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) {

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

OR better yet

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

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


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.