Backbone JS找到最小值

时间:2012-03-30 14:19:41

标签: backbone.js underscore.js

我有这个json填充我的模型集合(TableListCollectionTableModel)

{
    "tables": [
        {
            "tableId": 15,
            "size": 8,
            "occupiedSeats": 0,
            "stakes": {
                "smallBlindAmount": 10,
                "bigBlindAmount": 20,
                "minBuyInAmount": 20,
                "maxBuyInAmount": 200
            },
            "gameType": "HOLDEM",
            "gameSpeed": "NORMAL",
            "friends": []
        },
        {
            "tableId": 16,
            "size": 8,
            "occupiedSeats": 0,
            "stakes": {
                "smallBlindAmount": 20,
                "bigBlindAmount": 40,
                "minBuyInAmount": 20,
                "maxBuyInAmount": 200
            },
            "gameType": "HOLDEM",
            "gameSpeed": "NORMAL",
            "friends": []
        },
        {
            "tableId": 17,
            "size": 8,
            "occupiedSeats": 0,
            "stakes": {
                "smallBlindAmount": 40,
                "bigBlindAmount": 60,
                "minBuyInAmount": 20,
                "maxBuyInAmount": 200
            },
            "gameType": "HOLDEM",
            "gameSpeed": "NORMAL",
            "friends": []
        }
    ]
}

我想找到最小smallBlindAmount的表格。

我看到我可以使用_.min(),但我无法弄清楚我必须作为迭代器传递什么。

提前致谢。

1 个答案:

答案 0 :(得分:6)

直接在JSON上

var json=...
var min = _.min(json.tables,function(item) {
    return item.stakes.smallBlindAmount
});
console.log(min.stakes.smallBlindAmount);

或您的收藏

var json=...
var c=new Backbone.Collection(json.tables);
var m=c.min(function(model) {
    return model.get("stakes").smallBlindAmount
});
console.log(m.get("stakes").smallBlindAmount);

在这两种情况下,迭代器都用于提取要比较的值。