Comparing objects in strings
by David Hughes
JavaScript
function where(collection, source) {
var arr = [];
//Convert the source to a string
source = JSON.stringify(source);
source = source.replace(/[{}]/g, "");
for (var i = 0; i < collection.length; i++) {
//stringify each element in the array
stringed = JSON.stringify(collection[i]);
//Check to see if source is found within current element of collection
if (stringed.indexOf(source) > -1) {
arr.push(collection[i]);
}
}
console.log(arr);
return arr;
}
where([{
first: "Romeo",
last: "Montague"
}, {
first: "Mercutio",
last: null
}, {
first: "Tybalt",
last: "Capulet"
}], {
last: "Capulet"
});
//======= NOTES
//Two identical objects OR arrays are will return false when compared to each other, but will return true if first converted to strings(assuming contents of object are also the same)
//Comparing identical elements in different arrays will return true.
//Convert an object, that is in an array to a string, and then compare. To convert an object to a string use: JSON.stringify(object); Comparing 2 objects that are the same, converted to strings will return true.