admin管理员组文章数量:1312806
I have the following Object and I want to check if Type.ID contains value 6508 :
{
"item": {
"Feature": [
{
"ID": 85408,
"Status": {
"ID": 65,
},
"Type": {
"ID": 6508,
"Volume": null
},
"Manufacturer": null
},
{
"ID": 85409,
"Status": {
"ID": 65,
},
"Type": {
"ID": 6509,
"Volume": null
},
"Manufacturer": null
}
],
"Errors": {
"Result": 0,
"Message": ""
},
"RecordCount": 2
}
}
I can muster the following:
for (i = 0; i < data.item.Feature.length; i++) {
if (data.item.Feature[i].Type.ID == 6508)
return true;
}
return false;
How can I use underscore.js to do the same? The following doesn't work?
_.contains(data.item.Feature.Type.ID, 6508)
I have the following Object and I want to check if Type.ID contains value 6508 :
{
"item": {
"Feature": [
{
"ID": 85408,
"Status": {
"ID": 65,
},
"Type": {
"ID": 6508,
"Volume": null
},
"Manufacturer": null
},
{
"ID": 85409,
"Status": {
"ID": 65,
},
"Type": {
"ID": 6509,
"Volume": null
},
"Manufacturer": null
}
],
"Errors": {
"Result": 0,
"Message": ""
},
"RecordCount": 2
}
}
I can muster the following:
for (i = 0; i < data.item.Feature.length; i++) {
if (data.item.Feature[i].Type.ID == 6508)
return true;
}
return false;
How can I use underscore.js to do the same? The following doesn't work?
_.contains(data.item.Feature.Type.ID, 6508)
Share
Improve this question
asked Apr 2, 2017 at 7:22
adam78adam78
10.1k24 gold badges107 silver badges221 bronze badges
3 Answers
Reset to default 5You don't need underscore for this; example in plain JS.
data.item.Feature.some(function(x) { return x.Type.ID === 6508 });
Using @FakeRainBrigand JS code I've manged to achieve the same using underscore by doing the following:
_.some(data.item.Feature, function(f) {
return f.Type.ID == 6508;
})
Just a suggestion bro, if in case you want whole object (Inside 'Feature' List) not just the Boolean according to your search criteria, you can go this way as mentioned below.
var val = _.findWhere(data.item.Feature, {'Type': _.findWhere(_.pluck(data.item.Feature, 'Type'), {ID: 6509})});
This will return:
{
"ID":85409,
"Status":{
"ID":65
},
"Type":{
"ID":6509,
"Volume":null
},
"Manufacturer":null
}
本文标签: javascriptUnderscorejsCheck if Object Array contains valueStack Overflow
版权声明:本文标题:javascript - Underscore.js - Check if Object Array contains value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741915973a2404732.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论