JSON的示例结构:
{ "array_name1" : [
{"name":"John","age":"18","group":"user","country":"UK","hobby":"series","sport":"football"},
{"name":"Ted","age":"20","group":"user","country":"US"}, ...]}
{ "array_name2" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"Ted","age":"20","group":"user","country":"US", sport:"tennis"},
{"name":"David","age":"20","group":"user", sport:"tennis"},...]}
{ "array_name3" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"David","age":"20","group":"user", sport:"tennis"},...]}
我必须比较2个JSON数组对象。 我需要在2个不同的对象数组中比较具有相同名称的对象。 例如,我需要比较array_name1和array_name2,我需要检测一个新对象出现在array_name2中。此外,我需要检测John上的组从用户更改为admin的值。 如果我需要比较array_name2和array_name3,我需要检测到在array_name3上删除了用户Ted。
答案 0 :(得分:1)
试试这样..
var com = { "array_name1" : [
{"name":"John","age":"18","group":"user","country":"UK","hobby":"series","sport":"football"},
{"name":"Ted","age":"20","group":"user","country":"US"}]};
var com1 = { "array_name2" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"Ted","age":"20","group":"user","country":"US", "sport":"tennis"},
{"name":"David","age":"20","group":"user", "sport":"tennis"}]}
var com2 = { "array_name3" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"David","age":"20","group":"user", "sport":"tennis"}]};
var com3 = { "array_name3" : [
{"name":"John","age":"18","group":"admin","country":"UK","hobby":"series","sport":"football"},
{"name":"David","age":"20","group":"user", "sport":"tennis"}]};
console.log(com.array_name1 === com1.array_name2); // direct compare
function checkEqual(x,y) {
return JSON.stringify(x) === JSON.stringify(y);
}
console.log(checkEqual(com.array_name1, com1.array_name2));
console.log(checkEqual(com3.array_name3, com2.array_name3));