Javascript 比较 2 个 JSON 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4465244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:32:08  来源:igfitidea点击:

Compare 2 JSON objects

javascriptjsoncompare

提问by

Possible Duplicate:
Object comparison in JavaScript

可能的重复:
JavaScript 中的对象比较

Is there any method that takes in 2 JSON objects and compares the 2 to see if any data has changed?

是否有任何方法可以接收 2 个 JSON 对象并比较这 2 个对象以查看是否有任何数据已更改?

Edit

编辑

After reviewing the comments, some clarification is needed.

在查看评论后,需要进行一些澄清。

  1. 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

  2. My goal is to be able to compare 2 JSON object literals, simply put.

  1. JSON 对象定义为

    "一组无序的名称/值对。一个对象以{(左大括号)开始,以}(右大括号)结束。每个名称后跟:(冒号),名称/值对用,(逗号)分隔.” -- json.org

  2. 简单地说,我的目标是能够比较 2 个 JSON 对象文字。

I am not a javascript guru so if, in javascript, these are object literals, then I suppose that's what I should call them.

我不是 javascript 大师,所以如果在 javascript 中,这些是对象文字,那么我想这就是我应该称呼它们的原因。

I believe what I am looking for is a method capable of:

我相信我正在寻找的是一种能够:

  1. Deep recursion to find a unique name/value pair
  2. Determine the length of both object literals, and compare the name/value pairs to see if a discrepancy exists in either.
  1. 深度递归以找到唯一的名称/值对
  2. 确定两个对象文字的长度,并比较名称/值对以查看两者中是否存在差异。

采纳答案by jd.

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).

简单地解析 JSON 并比较两个对象是不够的,因为它不会是完全相同的对象引用(但可能是相同的值)。

You need to do a deep equals.

你需要做一个深度等于。

From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html- which seems the use jQuery.

来自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();
   }
});

Usage:

var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);

if (Object.deepEquals(anObj, anotherObj))
   ...