如何使用underscore.js过滤器获得结果?

时间:2015-05-04 09:07:36

标签: javascript underscore.js

这是测试数组:

var test = [
{
    "id": 1, 
    "team": [
        {
            "name": "Alex", 
            "age": 27, 
            "checked": true
        }, 
        {
            "name": "Bob", 
            "age": 35,
            "checked": false
        }
    ], 
    "checked": true
}, 
{
    "id": "2", 
    "team": [
        {
            "name": "Jack", 
            "age": 37, 
            "checked": false
        }, 
        {
            "name": "Tom", 
            "age": 29, 
            "checked": true
        }
    ], 
    "checked": true
}];

我想得到的结果是这样的数组:

result = [“Alex”,“Tom”];

结果数组包含团队中“checked”属性等于true的所有项。 我尝试使用underscore.js filter获得结果,但我无法得到正确的结果。 如果您有更好的解决方案,请告诉我。 这是我的代码:

_.filter(test, function(team) {
 _.filter(team, function(worker){
    if(worker.checked)
        return worker.name;
 });});

3 个答案:

答案 0 :(得分:4)

以下是如何在下划线和lodash中执行此操作:

Underscore jsfiddle

var result = _.chain(test).pluck('team').flatten().filter({checked:true}).value();

Lodash jsfiddle

var result = _(test).pluck('team').flatten().filter({checked:true}).value();

将团队数组放在一起,展平它们,以便拥有嵌套数组,对属性进行过滤,结果是包含名称的对象,并检查为true。如果你只想要这些名字,可以再做一次。

这是一个带有shorter filter and just giving back the names

的下划线版本
var result = _.chain(test).pluck('team').flatten().filter('checked').pluck('name').value();
// ["Alex", "Tom"]

答案 1 :(得分:0)

您只需使用forEach function来处理此

var test = [...];

var result = [];

test.forEach(function(item) {
    item.team.forEach(function(worker) {
        if(worker.checked) {
            result.push(worker.name);
        }
    })
})

console.log(result)
//Return ["Alex","Tom"]

答案 2 :(得分:-1)

One way to use filtering for multidimentional array is by using filter and any.

_.filter(test, function(team) {
    return _.any(team.team, function(player) {
        return player.checked;
    });
});
相关问题