2

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)

3 Answers 3

5

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

data.item.Feature.some(function(x) { return x.Type.ID === 6508 });
Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.