2

我想使用_.where下划线函数,但我似乎无法让它在对象数组上工作。我有以下json:

var Planets = [
        {name:"maths", percComp: "2", preReq: "english"},
        {name:"english", percComp: "20", preReq: "geog"},
        {name:"german", percComp: "20", preReq: "english"},
        {name:"history", percComp: "20", preReq: "german"},
        {name:"irish", percComp: "20", preReq: "geog"},
        {name:"geog", percComp: "20", preReq: ""},        
        {name:"french", percComp: "20", preReq: "spanish"},
        {name:"spanish", percComp: "57", preReq: "french"}          
    ];

然后我使用以下代码将每个代码添加到数组中:

$(jQuery.parseJSON(JSON.stringify(Planets))).each(function(){
        var planet = new Class.Planet(this, paper);
        universe.push(planet);            
    });

我正在尝试使用下划线从列表中获取项目,如下所示:

var planets = _.where(universe, {name: "maths"});

但我收到以下脚本错误:

Uncaught TypeError: Object function (a){return new j(a)} has no method 'where' 

编辑 你也可以使用类似的东西

var planets = _.filter(Planets, function(p){ return p.name === "maths"});
4

3 回答 3

4

_.where仅在 1.4.0 http://underscorejs.org/#where中可用

你必须使用 Varon 的建议_.find

或者您可以简单地使用 JS https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter

示例:http: //jsfiddle.net/4mxjb/2/

// returns an array with objects where their name 
// property is equal to 'maths'
Planets.filter(function(obj){
    return obj.name === 'maths'
}); 
于 2012-11-19T19:21:10.160 回答
3

使用 underscorejs 就可以得到这个星球

var planet = _.find(Planets, function(p) {return p.name == 'maths'});
于 2012-11-19T19:19:44.903 回答
1

只是为了消除旧答案中的混乱:

  1. _.find
    • 输入:比较函数
    • 返回第一个匹配元素;
  2. _.filter
    • 输入:比较函数
    • 返回所有匹配的元素;
  3. _.where
    • 输入:对象
    • 返回所有匹配的元素;
  4. _.findWhere
    • 输入:对象
    • 返回第一个匹配元素。

var Planets = [
    {name:"maths", percComp: "2", preReq: "english"},
    {name:"english", percComp: "20", preReq: "geog"},
    {name:"german", percComp: "20", preReq: "english"},
    {name:"history", percComp: "20", preReq: "german"},
    {name:"irish", percComp: "20", preReq: "geog"},
    {name:"geog", percComp: "20", preReq: ""},        
    {name:"french", percComp: "20", preReq: "spanish"},
    {name:"spanish", percComp: "57", preReq: "french"}        
];

console.log('---FIND---\n', // Returns only ONE matching element
  _.find(Planets, function(o){ return o.preReq === 'english'; })
);
console.log('---FILTER---\n', // Returns ALL matching elements
  _.filter(Planets, function(o){ return o.preReq === 'english'; })
);
console.log('---WHERE---\n', // Returns ALL matching elements
  _.where(Planets, {preReq: 'english'})
);
console.log('---FINDWHERE---\n', // Returns only ONE matching element
  _.findWhere(Planets, {preReq: 'english'})
);
<script
src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js">
</script>

于 2017-12-26T13:04:44.447 回答