yolo
yolo

Reputation: 2795

JavaScript JSON compare

There are two JSON var (JSON.parse'd already)

var acc http://pastebin.com/7DyfFzTx

var sit http://pastebin.com/vnZiVaDx

My objective is to loop each var to compare acc.items.site_name with sit.items.main_site.name to see if they are equal. If they are equal, then I need to store sit.items.main_site.site_url in a variable. I am using this code:

for(i=0; i < acc.items.length;i++)
{
  aname = acc.items[i].site_name;
  for(i=0; i < sit.items.length;i++)
    {
     sname = sit.items[i].main_site.name;
     if (aname == sname)
     alert("same "+aname);
    }
}

But the alert only logs "same Physics" . "Physics" is the first object in acc.items. This means that the loop is only comparing first acc.items but how do I make it compare the second and further on objects (e.g. "TeX - LaTeX")

Upvotes: 0

Views: 554

Answers (2)

blackcatweb
blackcatweb

Reputation: 1013

Well, you can start by using a different control variable for the outer and inner loops. :)

Also, notice how you are running through every element of the second object each time you consider an element in the first object- that doesn't seem like what you want to do.

Try reviewing this posting for a more modular method:

http://jsperf.com/recursive-vs-json-object-comparison

Upvotes: 4

BCoates
BCoates

Reputation: 1518

You're using the same variable for the inner and outer loop.

Give the second for loop a different variable name than i

Upvotes: 2

Related Questions