Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 228
Durgesh Suthar Avatar asked Apr 20 '26 11:04

Durgesh Suthar


1 Answers

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

like image 188
KooiInc Avatar answered Apr 22 '26 00:04

KooiInc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!