按特定值

时间:2016-05-24 14:36:00

标签: javascript json lodash

我发送的数据已经按照Laravel中的控制器到我的脚本文件的次数排序。我发送的Json数据看起来像这样:

{"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}}

但是当我在我的脚本文件中解析这样的json数据时,数据会再次随机出现:

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

然后我获得了如下所示的控制台数据:

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

1 个答案:

答案 0 :(得分:3)

您可以使用lodash#sortBy进行排序:

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

创建一个元素数组,按照每个iteratee中运行collection(Array | Object)中每个元素的结果按升序排序。此方法执行稳定排序,即保留相等元素的原始排序顺序。使用一个参数调用迭代:( 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>
&#13;
&#13;
&#13;