比较2个JSON对象 [英] Compare 2 JSON objects
问题描述
可能重复:
JavaScript中的对象比较
JSON对象并比较2以查看是否有任何数据更改了。
编辑
$ b b
无序的一组名称/值对
对象以{(左括号)
开头并以} 。每个
名称后面是:(冒号)和
名称/值对由
(逗号)分隔。 - json.org
我的目标是能够比较2个JSON对象字面量,只是放。
我不是一个javascript guru所以如果在JavaScript中,这些都是对象字面量,那么我想这就是我应该称之为它们。
我相信我正在寻找的是一个方法能够: / p>
- 深度递归以查找唯一的名称/值对
- 确定两个对象文字的长度,
A JSON object is defined as
"an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma)." -- json.org
My goal is to be able to compare 2 JSON object literals, simply put.
- Deep recursion to find a unique name/value pair
- Determine the length of both object literals, and compare the name/value pairs to see if a discrepancy exists in either.
简单地解析JSON和比较两个对象是不够的,因为
它不会是完全相同的对象引用(但可能是相同的值)。
你需要做一个深层的平等。
从 http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - 这似乎使用jQuery。
Object.extend(Object,{
deepEquals:function(o1,o2){
var k1 = Object.keys(o1).sort
var k2 = Object.keys(o2).sort();
if(k1.length!= k2.length)return false;
return k1.zip(k2,function(keyPair){
if(typeof o1 [keyPair [0]] == typeof o2 [keyPair [1]] ==object){
return deepEquals(o1 [keyPair [0]],o2 [keyPair [1]])
} else {
return o1 [keyPair [0]] == o2 [keyPair [1]];
}
})。all();
}
});
用法:
var anObj = JSON.parse(jsonString1);
var anotherObj = JSON.parse(jsonString2);
if(Object.deepEquals(anObj,anotherObj))
...
Possible Duplicate:
Object comparison in JavaScript
Is there any method that takes in 2 JSON objects and compares the 2 to see if any data has changed?
Edit
After reviewing the comments, some clarification is needed.
I am not a javascript guru so if, in javascript, these are object literals, then I suppose that's what I should call them.
I believe what I am looking for is a method capable of:
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
这篇关于比较2个JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!