Marco Marco - 6 months ago 28
JSON Question

Sorting json objects by specific value

I am sending data that I have already sorted by number of counts, from my controller in Laravel to my script file. Json data that I am sending looks like this:

{"5":{"title":"Coop post title","summary":"dbsbsb","count":5},
"7":{"title":"Example article","summary":"fdsbdfsbsffd","count":5},
"6":{"title":"Coop's post","summary":"sdbadbb","count":3},
"0":{"title":"sdvsdv","summary":"dsvsdv","count":2},
"4":{"title":"sdvsdv","summary":"dsvsdv","count":1}}


But when I parse json data like this in my script file data gets random again:

var cleanData = $.parseJSON(data);
console.log(cleanData);


And then I get in console data that looks like this:

Object {0: Object, 4: Object, 5: Object, 6: Object, 7: Object}
0:Object
count:2
summary:"dsvsdv"
title:"sdvsdv"
__proto__:Object
4:Object
count:1
summary: "dsvsdv"
title: "sdvsdv"
__proto__:Object
5:Object
count:5
summary: "dbsbsb"
title: "Coop post title"
__proto__: Object
6:Object
count:3
summary: "sdbadbb"
title: "Coop's post"
__proto__: Object
7:Object
count:5
summary: "fdsbdfsbsffd"
title: "Example article"
__proto__: Object

Answer

You can sort using lodash#sortBy:

_.sortBy(collection, [iteratees=[_.identity]])

Creates an array of elements, sorted in ascending order by the results of running each element in a collection (Array|Object) thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value).

var cleanData = {"5":{"title":"Coop post title","summary":"dbsbsb","count":5},"7":{"title":"Example article","summary":"fdsbdfsbsffd","count":5},"6":{"title":"Coop's post","summary":"sdbadbb","count":3}, "0":{"title":"sdvsdv","summary":"dsvsdv","count":2}, "4":{"title":"sdvsdv","summary":"dsvsdv","count":1}};

cleanData = _.sortBy(cleanData, ['count']);
console.log(cleanData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>