I have this code:
$('#find').click(function(){
if(first.val() != '' && second.val() != ''){
$.getJSON(urlPersonSearch + first.val() + "?callback=?", function(json) {
firstId = (json[0].id != undefined) ? json[0].id : '';
if(firstId != '') result = grabMovies(firstId);
var i = result[0].filmography.length;
while(i--){
movies[result[0].filmography[i].id] = result[0].filmography[i].name;
}
});
$.getJSON(urlPersonSearch + second.val() + "?callback=?", function(json) {
secondId = (json[0].id != undefined) ? json[0].id : '';
if(secondId != '') result = grabMovies(secondId);
var i = result[0].filmography.length;
while(i--){
movies[result[0].filmography[i].id] = result[0].filmography[i].name;
}
});
}
});
function grabMovies(id){
$.getJSON(urlPersonResult + id + "?callback=?", function(json) {
return json;
});
}
Now, what I’m trying to do, is end up with an object with ID and Movie Name as the key/value. Ultimately i’m trying to get an object which contains only the matches between the two json results. Ie.
if the first had a result of
23 = hello,
283 = goodbye,
and the second had a result of
23 = hello,
294 = bye
I would end up with an object of
23 = hello
Has anyone got any advice on how to do this?
You’re looking for an array intersection function. Underscore.js has one. So I was all ready to tell you to use that, but it won’t do for this purpose. Look what I tried:
The underlying problem here is object equivalency in JavaScript. Note also that
Two JavaScript objects are not equivalent to each other, even if they have the same keys and values. This has to do with the object literal in Javascript calling a constructor under the hood, and thereby reserving a new loctation in memory.
The solution
Underscore appears to have a bug in its _.indexOf method. Other than that, it’s a fantastic library and I suggest you use it. I would just extend it with the following:
Now, you can run
_.deepIntersection(a,b)like so: