Compare 2 JSON objects(比较 2 个 JSON 对象)
问题描述
可能重复:
JavaScript 中的对象比较
是否有任何方法可以接收 2 个 JSON 对象并比较这两个对象以查看是否有任何数据发生变化?
Is there any method that takes in 2 JSON objects and compares the 2 to see if any data has changed?
编辑
查看评论后,需要澄清一下.
After reviewing the comments, some clarification is needed.
一个 JSON 对象被定义为
A JSON object is defined as
一组无序的名称/值对.对象以 { 开头(左大括号)并以 }(右大括号)结尾.每个名称后跟:(冒号)和名称/值对由 , 分隔(逗号)." -- json.org
"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
简单地说,我的目标是能够比较 2 个 JSON 对象字面量.
My goal is to be able to compare 2 JSON object literals, simply put.
我不是 javascript 专家,所以如果在 javascript 中这些是对象字面量,那么我想我应该这样称呼它们.
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:
- 深度递归查找唯一的名称/值对
- 确定两个对象字面量的长度,并比较名称/值对以查看两者是否存在差异.
推荐答案
仅仅解析 JSON 并比较两个对象是不够的,因为它不会是完全相同的对象引用(但可能是相同的值).
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.
来自 http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - 这似乎是使用 jQuery.
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 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较 2 个 JSON 对象


- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01
- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01