简体   繁体   English

使用Underscore.js查询数组

[英]Query Array with Underscore.js

I have two JavaScript arrays. 我有两个JavaScript数组。 My first array looks like this: 我的第一个数组如下所示:

teams: [
  { id: 1, name:'Flyers' },
  { id: 2, name:'Hawks' },
  { id: 3, name:'Bats' },
  { id: 4, name:'Ninjas' },
  { id: 5, name:'Seals' }
];

selected: ["1", "3", "4"];

How do I return an array of teams that have an ID in selected? 如何返回一组已选择ID的球队? I'm trying to do this with underscore.js Currently, I have: 我正在尝试使用underscore.js执行此操作,目前,我有:

  var selected = _.filter(teams, function (team) {
    return _.contains(selected, team.id);
  });

However, that's not working. 但是,这不起作用。 What am I doing wrong? 我究竟做错了什么?

由于team.id是一个数字,因此它永远不会出现在字符串数组中。

I would use a two step process for this. 我将为此使用两步过程。 Using _.contains inside a loop is a bad habit and you can skip it by precomputing a simple lookup table using _.object : 在循环中使用_.contains是一个坏习惯,您可以通过使用_.object预计算一个简单的查找表来跳过它:

var selected_has = _(selected).object(selected);

Since all the values in selected are truthy, we can say things like if(select_has[id]) to see if id is in selected . 由于selected中的所有值都是真实的,因此我们可以说if(select_has[id])来查看id是否在selected

var matches = _(teams).filter(function(o) {
    return selected_has[o.id]
});

Of course, you pay a little bit for the type conversions but you gain expressiveness. 当然,您为类型转换花了一点钱,但是却获得了表达能力。

Demo: http://jsfiddle.net/ambiguous/b4XyU/ 演示: http//jsfiddle.net/ambiguous/b4XyU/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM