wilsonpage
wilsonpage

Reputation: 17610

Best way to match values in nested objects JS, jQuery

Ok I have a big JS object that contains data I need within 3 tiers:

ob = {
  x1:{
    y11:{a:foo,b:bah},
    y22:{a:foo,b:bah},
    y33:{a:foo,b:bah}
  }
  x2:{
    y11:{a:foo,b:bah},
    y22:{a:foo,b:bah},
    y33:{a:foo,b:bah}
  } 
  x3:{
    y11:{a:foo,b:bah},
    y22:{a:foo,b:bah},
    y33:{a:foo,b:bah}
  }
}

I also have an array of values:

var array = [foo,bah,foo,bah];

I need to check if the values in this array match any of the values at the third tier of my big JS object and pull out some sibling values that i require. I understand this is possible with 3 nested $.each loops. But is that the most efficient way to do this job?

Hope this is clear, appreciate the help!

Upvotes: 0

Views: 829

Answers (1)

jAndy
jAndy

Reputation: 236022

You need three nested loops to do this. No way around.

for(var level1 in ob) {
    for(var entry in level1) {
        for(var value in entry) {
            if( $.inArray(entry[value], array) > -1 ) {
                // match
            }
        }
    }
}

Upvotes: 2

Related Questions