2016-11-02 160 views
1

如何僅顯示3個結果?我用for-Loop試過,但它總是說NaN。我使用Lodash。這是我的jsFiddle:https://jsfiddle.net/kxohm0qh/限制json結果

我只想顯示3條結果。就像我說的,我試了一下for循環,當我不是使用_.map這樣的:

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

它工作在控制檯。但如果我這個整合的for循環中的jsfiddle,它只是打破:(我也搜索在Lodash限制功能,但它是無望

回答

1

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

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);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.6/lodash.min.js"></script>