在JavaScript中迭代一个循环遍历多个对象

时间:2014-10-05 13:33:29

标签: javascript json loops iteration for-in-loop

我有两个JSON对象obj1& obj2。我想比较这些对象的值。

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

我想做这样的事情:

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

我的输出应该是:

Test1:Test1
hey:20
yeah:lol

1 个答案:

答案 0 :(得分:4)

只需使用密钥(Object.keys仅返回可枚举的属性):

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