1

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 ?

2
  • mm if arr = [] and without populating it, you are trying to search $.inArray(newData, arr) which I think will always return you -1 Commented Apr 5, 2012 at 14:36
  • yeah I want to check if newData exists in the arr - that is, whether it's one of the myUrl ? Commented Apr 5, 2012 at 14:40

2 Answers 2

1

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
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

one quick question - the data returns like [object{id='1', myUrl=''}] so using this.MyUrl doesn't seem to work ? Think it needs this[0].myUrl ?
0

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/

2 Comments

sure so I am trying to see whether newData is within the array - as myUrl contains urls and I want to try to see if newData is one of these ?
well -1 just says it's not in the array - therefore it will push data to the array and then when it's called again it can search ? however, I'm unsure how to search the updated array of objects like [[object{id='1', myUrl=''}], [object{id='2', myUrl='' }]]

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.