1

If I have this object:

DropIds = [
  {
    "studentId": 5,
    "dropboxItems": [
        {
            "dropBoxId": 230,
        }
    ]
  },
  {
    "studentId": 4,
    "dropboxItems": [
        {
            "dropBoxId": 585,
        },
        {
            "dropBoxId": 586,
        }
    ]
  }
]

And I try to run this code:

var result = $.grep(DropIds, function(e){
    return e.dropboxItems[0].dropBoxId == 585;
});

it will return a result, however if I change it from 585 to 586 the result is empty.

http://jsfiddle.net/tdb70f50/1/

So it looks like my code will only check the first object in the array.

How can I grab the object when there is more than one dropBoxId?

Thanks!

1
  • 2
    You need to also loop through the items of dropboxItems rather than just look at the first item. Commented Jan 16, 2015 at 22:42

3 Answers 3

3

You need to check all the items in the array, not just the 0 index, you can use Array.prototype.filter

var result = DropIds.filter(function(item) {
    return item.dropboxItems.filter(function(box) {
        return box.dropBoxId == 586
    }).length
});

Demo: http://jsfiddle.net/56h7daod/

Sign up to request clarification or add additional context in comments.

1 Comment

You could replace the inner .filter() with .some() (and therefore remove the .length). This will only check box items until it finds the first match. fiddle
0

That's because you are only testing the first element (zero as index);

return e.dropboxItems[0].dropBoxId == 585;

you have to loop inside elements testing each object;

var result = $.grep(DropIds, function(e){
    if(!e.dropboxItems) return false;

    for(var i = 0; i < e.dropboxItems.length; i++) {
        if(e.dropboxItems[i].dropBoxId == 586) return true
    }

    return false;
});

http://jsfiddle.net/tdb70f50/2/

Comments

0

In conjunction with the answers already provided, you can make good use of mapping and reducing to extract an array of nested dropBoxItems and then perform a search for a given dropBoxId, ie:

function getByDropBoxId(id, dropId) {
  return dropId
    // Pluck the nested arrays into a 2d array
    .map(function (dropId) {
      return dropId.dropboxItems;
    })
    // flatten / reduce them to a single array.
    .reduce(function (soFar, dropBoxItems) {
      return soFar.concat(dropBoxItems);
    }, [])
    // filter out the ones you are looking for and return the first.
    .filter(function(dropBoxItem) {
      return dropBoxItem.dropBoxId === id; 
    })[0];
};

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.