adam78
adam78

Reputation: 10068

Underscore.js - Check if Object Array contains value

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)

Upvotes: 2

Views: 5661

Answers (3)

Anand Gupta
Anand Gupta

Reputation: 366

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
}

Upvotes: 0

adam78
adam78

Reputation: 10068

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

Upvotes: 3

Brigand
Brigand

Reputation: 86220

You don't need underscore for this; example in plain JS.

data.item.Feature.some(function(x) { return x.Type.ID === 6508 });

Upvotes: 5

Related Questions