Reputation: 19251
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
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
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".
Upvotes: 0