Andy
Andy

Reputation: 19251

jQuery Searching an Array of Arrays?

I have the following and I am trying to figure out how to search the array of objects - the call() function is called multiple times ?

var arr = [];
var newData;

function call() {
    newData = $('a').attr('href');

    if($.inArray(newData, arr) == -1) {
      $.post('/blah', function(data) {
          arr.push(data);
      });
    }
}

data is like [object{ }] so arr becomes [[object{id='1', myUrl=''}], [object{id='2', myUrl='' }]].

What I am trying to figure is out whether newData is contained within the arr ?

Upvotes: 1

Views: 2492

Answers (2)

gen_Eric
gen_Eric

Reputation: 227190

If the array contains objects, $.inArray will not work. This is because objects are only equal if they are the same object, not just contain the same values.

$.inArray won't work here also because newData is a string. It's not gonna search inside each object for you, you need to that yourself, with your own loop.

Something like this:

newData = $('a').attr('href');
$.each(arr, function(){
    if(this.myUrl === newData){
        $.post('/blah', function(data) {
            arr.push(data);
        });
        return false; // break once a match is found
    }
});

Upvotes: 1

Kris Krause
Kris Krause

Reputation: 7326

The Array arr will contain a list of objects. Why would newData be "contained" within the arr? They are two separate variables.

Update - Upon further inspection this line is no good:

if($.inArray(newData, arr) == -1) {

You are essentially saying look for newData in the arr (which is empty).

Update - Here is some sample code that should work. Here I am treating data as a plain old object (not an array of objects) with a property named "url".

http://jsfiddle.net/nWh6N/

Upvotes: 0

Related Questions