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!

1

3 Answers 3

1

Try the following

var inArray = false;
for (var i = 0; i < tabArray.length; i++) {
  if (tabArray[i].url === '/pages/publish') {
    inArray = true;
    break;
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Careful accessing .url on every element of the array like this, it might not always be defined.
@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.
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.
You guys are right, I guess I was speaking more to my own coding style rather than what is necessarily syntactically sound. Good catch.
1

This should work:

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

console.log(inArray); // true

1 Comment

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

1 Comment

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

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.