I have 2 JSON objects and want to check if a value from the first one appears anywhere in the second one, and if it does, push it into an array. I've tried to write a for loop to do this, but somehow I can't seem to get it right.
Can anybody point out what I'm doing wrong?
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);
you can compare both by there values
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);
Note: For numbers as key you should use obj[number]
not 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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.