Durgesh Suthar
Durgesh Suthar

Reputation: 3274

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

Upvotes: 2

Views: 12298

Answers (1)

KooiInc
KooiInc

Reputation: 122936

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 ...

Upvotes: 9

Related Questions