如何在underscore.js中简化两个嵌套的findWhere?

时间:2016-08-19 01:08:25

标签: javascript arrays object underscore.js

假设我有一个这样的对象:

var data = [
    {   
        "class": 101,
        "students": [
            { "name": "bob", "grade": 98 },
            { "name": "alice", "grade": 87 }
        ]
    },
    {   
        "class": 103,
        "students": [
            { "name": "mike", "grade": 73 },
            { "name": "bill", "grade": 77 }
        ]
    }
]

使用underscore.js是否有更简单的方法?

_(_(data).findWhere({"class": 101}).students).findWhere({"name": "alice"}).grade // is 87

1 个答案:

答案 0 :(得分:-1)

希望这有帮助

var student101 = _.findWhere(data, { "class": 101 }).students;

上面的代码为您提供了这个            {" name":" bob"," grade":98},            {" name":" alice"," grade":87}

这样做我们得到了

_.find(_.findWhere(data, { "class": 101 }).students, function(num){ return  num.name  == 'alice'}).grade 

最终结果87