Underscore.js:findWhere具有嵌套属性值 [英] Underscore.js : findWhere with nested property value

查看:360
本文介绍了Underscore.js:findWhere具有嵌套属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何进行以下过滤:

[{
    "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
    }]
}]

只能获得那些 tax.id 17 ,如下所示:

to get only those where tax.id is 17, as per below:

[
    {
        "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
            }
        ]
    }
]

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

Currently I use the method below, but maybe there is more clean way of going about this?

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

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

任何建议都非常感谢。

Any suggestion much appreciated.

推荐答案

您可以使用 _。过滤器和<$的组合c $ c> _。其中

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

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

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

Thanks to @GruffBunny. A more efficient way is to use _.some to avoid looping through all tax items:

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

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

这篇关于Underscore.js:findWhere具有嵌套属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆