2

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
3
  • You need a nested loop Commented Oct 5, 2014 at 13:35
  • obj2.hasOwnProperty(key2) Commented Oct 5, 2014 at 13:35
  • @Johan but how can I compare respective values of key for both? I want to iterate both object at same time so that respective values can be compared. Commented Oct 5, 2014 at 13:40

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.