javascript - Underscore.js : findWhere with nested property value -


how go filtering below:

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

to tax.id 17, 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 use method below, maybe there more clean way of going this?

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

demo here: http://jsfiddle.net/7gccz/2/

any suggestion appreciated.

you may use combination of _.filter , _.where

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

see demo: http://jsfiddle.net/hcvxp/

update


thanks @gruffbunny. more efficient way use _.some avoid looping through tax items:

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

see demo: http://jsbin.com/putefarade/1/edit?html,js,console


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -