Search code examples
javascriptjsonloopsiterationfor-in-loop

Iterate one for in loop through multiple objects in JavaScript


I have two JSON object obj1 & obj2. I want to compare values of these objects.

var obj1 = {"Don":"Test1","is":"hey","here":"yeah"};
var obj2 = {"Don":"Test1","is":"20","here":"lol"};

I want to do something like this:

for( var key1 in obj1 && var key2 in obj2){
  if(obj1.hasOwnProperty(key1) && obj2.hasOwnProperty(key2))
    console.log(obj1[key1]+ " : " + obj2[key2]);
}

My output should be:

Test1:Test1
hey:20
yeah:lol

Solution

  • Just use the keys (Object.keys returns only enumerable properties):

    var obj1 = {"Don":"Test1","is":"hey","here":"yeah"};
    var obj2 = {"Don":"Test1","is":"20","here":"lol"};
    Object.keys(obj1).forEach( function (key) { console.log(obj1[key]+':'+obj2[key]); } );
    

    See also ...