I have a dictionary of objects like this:
originalJson = {
"0":{
"width":55,
"offset":152
},
"A":{
"width":66,
"offset":0
},
"B":{
"width":66,
"offset":76
}
};
I want to sort them by the offset property, so that the resulting object should look like this:
sortedJson = {
"A":{
"width":66,
"offset":0
},
"B":{
"width":66,
"offset":76
},
"0":{
"width":55,
"offset":152
}
};
Note that "A" and "B" would come before "0" because their offset is lower.
I believe that I'd need to chain a few iterations together in lodash to accomplish this. Here's where I've got:
var originalJson = {
"0":{
"width":55,
"offset":152
},
"A":{
"width":66,
"offset":0
},
"B":{
"width":66,
"offset":76
}
};
var sortedJson = _.chain(originalJson)
.map(function (val, key) {
return { character: key, details: val };
})
.sortBy(function(o) {
return o.details.offset;
})
.keyBy('character')
.mapValues('details')
.value();
$('#console').append(JSON.stringify(sortedJson,false,2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>
<pre id="console">
</pre>
Unfortunately, it just returns the objects in the same order as before. Thanks for any help in advance!