1

I have an object built up like so:

tabArray.push({'linkId': 'tabBuild', 'id': 'columnRight','url': '/pages/publish/', 'content':response});

How can i use jQuery/javascript to do a test on that object to see if it contains a certain URL?

I tried this: if($.inArray('/pages/publish/', tabArray) > -1) alert('its in there');

But to no avail!

benhowdle89
  • 36,900
  • 69
  • 202
  • 331
  • possible duplicate of [Find object by id in array of javascript objects](http://stackoverflow.com/questions/7364150/find-object-by-id-in-array-of-javascript-objects) – Felix Kling Sep 19 '11 at 15:59

3 Answers3

1

Try the following

var inArray = false;
for (var i = 0; i < tabArray.length; i++) {
  if (tabArray[i].url === '/pages/publish') {
    inArray = true;
    break;
  }
}
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    Careful accessing .url on every element of the array like this, it might not always be defined. – Skylar Anderson Sep 19 '11 at 16:00
  • 4
    @Skylar if it's not defined then it should returned `undefined` and fail the comparison with the string literal. I don't see how this will cause a problem. – JaredPar Sep 19 '11 at 16:01
  • 1
    It's OK if `url` is not defined. Accessing it in this way will return `undefined`, which is not `===` to `'/pages/publish'`, and the code will continue on its merry way. – FishBasketGordo Sep 19 '11 at 16:02
  • You guys are right, I guess I was speaking more to my own coding style rather than what is necessarily syntactically sound. Good catch. – Skylar Anderson Sep 19 '11 at 16:06
1

This should work:

var inArray = !!$.grep(tabArray, function(item) {
        return item.url === '/pages/publish/';
    }).length;

console.log(inArray); // true
jmar777
  • 38,796
  • 11
  • 66
  • 64
  • Thanks. Should probably also be a -1 for not short-circuiting once a match is found, but iterations are fast and I *usually* go for readability if the performance tradeoff is minimal. – jmar777 Sep 19 '11 at 16:11
0

$.inArray won't work as it is only meant to search an array of strings while your array is an array of objects. You can create your own in array method.

var inURLArray = function(url, array) {
  for(var i in array) {
    if(array[i].url && array[i].url === url)
    return true;
  }
  return false;
}
Skylar Anderson
  • 5,643
  • 1
  • 25
  • 34
  • Why are you using `==` here instead of `===`? I don't believe the `array[i].url &&` portion is necessary. If `array[i].url` isn't defined then it will return `undefined` and fail the comparison with `url` – JaredPar Sep 19 '11 at 16:03