-1

I have created three functions, that can make two separate arrays with the matching keys and the matching properties. I would like to use those two arrays to create a new object with all of the matching pairs. Below I included the functions I have so far.

I am a beginner in Javascript ( which is most likely already apparent) so if you can explain each step thoroughly and not get to complex I would greatly appreciate it.

function contains(array, obj_to_check){
 for(var i = 0; i < array.length; i ++) {
  if (array[i] == obj_to_check) {
   return true;
  }
 } 
}
function sharedKeys(obj1, obj2) {
 var obj1Keys = Object.keys(obj1);
 var obj2Keys = Object.keys(obj2);
 var sharedArray = [];
 for( var x = 0; x < obj1Keys.length; x++){
  if (contains(obj2Keys, obj1Keys[x])){
  sharedArray.push(obj1Keys[x]);
  }
 }
 return sharedArray;
}
function sharedProperties(obj1, obj2) {
 var obj1Props = [];
 var obj2Props = [];
 var propertiesArray = [];
 for(var i in obj1)
  obj1Props.push(obj1[i]);
 for(var x in obj2)
  obj2Props.push(obj2[x]);
 for (var y = 0; y < obj1Props.length; y ++){
  if(contains(obj1Props, obj2Props[y])){
   propertiesArray.push(obj2Props[y])
  }
 }
 return propertiesArray;
}
Arjun
  • 226
  • 5
  • 20
Paul Duca
  • 31
  • 6
  • 1
    When a match is found, create a object. For example, you `.push` when a match is found, but you can `create an object as well. – Aaron Aug 29 '16 at 17:48
  • Some example input and an example of the desired output from that input would be helpful in answering your question. – Useless Code Aug 30 '16 at 08:25

1 Answers1

-1

You are comparing two objects, not two values. The only way that your == comparison works here is if both of them refer to the same object. You need to check and see if every properties and fields of those two objects are equal. Besides, check this thread about comparison in JavaScript.

Community
  • 1
  • 1
Saeid
  • 1,573
  • 3
  • 19
  • 37
  • I think the best way to compare to objects equity in JavaScript is by converting them to JSON string. Json Stringify will do the work for you. – Saeid Aug 29 '16 at 17:55
  • JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string. JSON.parse turns a string of JSON text into a Javascript object. – Saeid Aug 29 '16 at 17:55
  • 1
    `JSON.stringify` is not a safe way to compare objects because it doesn't iterate properties in any well-defined order. Even if you called it passing the same object, `JSON.stringify` is not guaranteed to always return the same result (but it will on most implementations, yes). – Oriol Aug 29 '16 at 18:37
  • Good point. @Oriol. Maybe it's better to have a primary key (surrogate key) on each object and only compare that. Anyway. It's completely design decision. – Saeid Aug 29 '16 at 19:31