Underscore.js:findWhere具有嵌套属性值

Ila*_*sda 24 javascript underscore.js

我如何进行以下过滤:

[{
    "id": 100,
    "title": "Tlt1",
    "tax": [{
        "name": "Tax1",
        "id": 15
    }, {
        "name": "Tax1",
        "id": 17
    }]
}, {
    "id": 101,
    "title": "Tlt2",
    "tax": [{
        "name": "Tax2",
        "id": 16
    }]
}, {
    "id": 102,
    "title": "Tlt3",
    "tax": [{
        "name": "Tax3",
        "id": 17
    }, {
        "name": "Tax3",
        "id": 18
    }]
}]
Run Code Online (Sandbox Code Playgroud)

得到的只有那些tax.id17,按如下:

[
    {
        "id": 100,
        "title": "Tlt1",
        "tax": [
            {
                "name": "Tax1",
                "id": 15
            },
            {
                "name": "Tax1",
                "id": 17
            }
        ]
    },
    {
        "id": 102,
        "title": "Tlt3",
        "tax": [
            {
                "name": "Tax3",
                "id": 17
            },
            {
                "name": "Tax3",
                "id": 18
            }
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

目前我使用下面的方法,但也许还有更简洁的方法来解决这个问题?

var arr = [];
_(data).each(function (v1, k1) {
    _(v1.tax).each(function (v2, k2) {
        if (v2.id == id) {
            arr.push(v1);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

在这里演示:http://jsfiddle.net/7gcCz/2/

任何建议都非常感谢.

Kir*_*ril 47

您可以使用的组合_.filter_.where

_.filter(data, function(obj) {
    return _.where(obj.tax, {id: ID_TO_FIND}).length > 0;
})
Run Code Online (Sandbox Code Playgroud)

见演示:http://jsfiddle.net/hCVxp/

更新


感谢@GruffBunny.更有效的方法是使用_.some以避免遍历所有tax项目:

var arr = _.filter(data, function(obj) {
    return _.some(obj.tax, {id: ID_TO_FIND});
});
Run Code Online (Sandbox Code Playgroud)

请参阅演示:http://jsbin.com/putefarade/1/edit?html,js,console

  • 使用`下划线',First Roadbump,谷歌第一链接,FTW的拳头时间! (5认同)

Gru*_*nny 19

使用_.filter查找候选项,使用_.some检查集合中是否存在项:

var filteredList = _.filter(list, function(item){
    return _.some(item.tax, { id: 17 });
});
Run Code Online (Sandbox Code Playgroud)