限制json

时间:2016-11-02 11:12:22

标签: javascript json for-loop html-lists lodash

如何只显示3个结果?我用for-Loop尝试了它,但它总是说NaN。我正在使用 Lodash 。这是我的jsFiddle:https://jsfiddle.net/kxohm0qh/

我只想显示3个结果。就像我说的那样,当我没有像这样使用_.map时,我尝试使用for-Loop:

for(var i = 0; i<3; i++){
var sorted = _.sortBy(data.car, 'roads').reverse();
console.log(sorted[i]);
}

它在控制台中有效。但是如果我在jsFiddle中将这个for-Loop集成,它就会破坏:(。我也在Lodash中搜索限制函数,但它没有希望。

1 个答案:

答案 0 :(得分:1)

使用_.take()限制结果:

&#13;
&#13;
var data = {
  "cars": [{
    "number": 5,
    "car_name": "Mercedes",
    "roads": 55
  }, {
    "number": 6,
    "car_name": "Ford",
    "roads": 41
  }, {
    "number": 9,
    "car_name": "Darcia",
    "roads": 36
  }, {
    "number": 3,
    "car_name": "BMW",
    "roads": 61
  }, {
    "number": 11,
    "car_name": "Nissan",
    "roads": 25
  }]
};

var sorted = _.take(_.reverse(_.sortBy(data.cars, 'roads')), 3);

console.log(sorted);

/** you can also use a chain **/

var sortedchained = _(data.cars)
  .sortBy('roads')
  .reverse()
  .take(3)
  .value();

console.log(sortedchained);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>
&#13;
&#13;
&#13;