Reputation: 187
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?
Upvotes: 4
Views: 1921
Reputation: 2654
I achieved this by setting a key
property on each object
within the _.sortBy()
- not ideal but one solution
_.sortBy(object, function(item, key) {
item.key = key;
return item.sortattribute;
});
Upvotes: 2
Reputation: 1129
I don't think that you can do this with a single call to _.sortBy().
However, you can accomplish it in two steps:
Here is an example JSBIN
The underlying problem is that objects are unordered collections of properties.
Upvotes: 2