简体   繁体   中英

How can I get the result with underscore.js filter?

Here is the test array:

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
}];

And the result that I want to get is an array like this:

result = ["Alex", "Tom"];

The result array contains all items that the "checked" attribute equals to true in team. I try to get the result with the underscore.js filter , but I cannot get the correct result. If you have a better solution, please tell me. Here is my code:

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

Here's how you can do it in both underscore and 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();

Take the team arrays together, flatten them so you have the nested arrays, filter on the property and the result are the objects containing the name and checked being true. If you want just the names, do another pluck.

Here's an underscorejs version with a shorter filter and just giving back the names :

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

You can simply use forEach function to handle this

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"]

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;
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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