javascript检查一次是否存在2个JSON对象中的键值

时间:2015-08-19 08:46:39

标签: javascript json

我有2个JSON对象,想要检查第一个中的值是否出现在第二个中的任何位置,如果是,则将其推入数组。我试图写一个for循环来做这件事,但不知何故我似乎无法做到这一点。

有人能指出我做错了吗?

var JSON1 = [{
    "1": "1",
        "2": "2"
}, {
    "1": "3",
        "2": "4"
}];

var JSON2 = [{
    "1": "1",
        "2": "2"
}, {
    "1": "3",
        "2": "4"
}];

var matching = [];

for (var key in JSON1) {
    if(JSON2[.hasOwnProperty(JSON1[key].1) ) {
		matching.push(JSON1[key].1);
	}
}

console.log(matching);

2 个答案:

答案 0 :(得分:0)

您可以通过值来比较

var JSON1 = [{
    "1": "1",
        "2": "2"
}, {
    "1": "3",
        "2": "4"
}];

var JSON2 = [{
    "1": "1",
        "2": "2"
}, {
    "1": "3",
        "2": "4"
}];

var matching = [];



for(x in JSON1) {
  for(y in JSON1[x]){
    if(JSON1[x][y] ==  JSON2[x][y]){
       matching.push(JSON1[x][y]);
       }
  }
}



console.log(matching);

答案 1 :(得分:0)

注意:要将数字作为键,您应使用obj[number]而不是obj.number

var JSON1 = [{
    "1": "1",
        "2": "2"
}, {
    "1": "3",
        "2": "4"
}];

var JSON2 = [{
    "1": "1",
        "2": "2"
}, {
    "1": "3",
        "2": "4"
}];

var matching = [];

for (var key in JSON1) {
    for(var k in JSON1[key]){
        if(key in JSON2 && k in JSON2[key] && JSON1[key][k] == JSON2[key][k]) {
            matching.push(JSON1[key][k]);
        }
    }
}

console.log(matching);