Javascript JSON比较/差异? [英] Javascript JSON comparison/diff?

查看:68
本文介绍了Javascript JSON比较/差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下2个json对象:

Say I have the following 2 json objects:

JSON A:
{
"Field A":"1",
"Field B":"2",
"Field D":"Something",
"Field E":"6"
}

JSON B:
{
"Field A":"1",
"Field B":"2",
"Field C":"3",
"Field D":"Different"
}

样本功能:函数(jsonstringA,jsonstringB)

Sample Function: function (jsonstringA, jsonstringB)

示例(如果将JSON A和JSON B用作参数)

Example (If JSON A and JSON B used as parameters):

返回一个新的JSON对象,其中包含:

Returns a new JSON object containing:

{
"Field C":"3", // because function sees jsonstringB had no "Field C"
"Field D": "Different" // sees jsonstringB had a different value for "Field D"
}

请注意,它使用jsonstringA作为比较的基础,因此该函数仅返回缺少的字段和jsonStringB的值.这就是为什么不返回字段E"及其值的原因.

Note that it is using jsonstringA as the base of the comparison, so the function returns only the fields missing and values of jsonStringB. That is why "Field E" and its value is not returned.

如果可能的话,提供返回包含已更改值的json对象的函数的最佳方法是什么?

What is the best way if possible to come up with a function that returns a json object containing values that have changed?

我尝试过的内容:我尝试通过手动指定要检查的字段来进行比较,但是我想做一些事情,要求我不要对字段"进行硬编码,因为它效率很低,每次我向JSON添加新字段时B,我必须在我要寻找的领域中进行硬编码...这就是为什么我要寻找更轻松的事情.

WHAT I HAVE TRIED: I have tried doing a comparison by manually specifying the fields that I am trying to check for, but I would like to have something that requires me to not hardcode the "Fields" as it is very inefficient and everytime I add a new field to JSON B, I have to hardcode in the field I am looking for... that is why I am looking for something less of a pain.

推荐答案

创建这样的函数并不难.只需遍历第二个对象中的每个字段,如果第一个对象中不存在该字段或该值与第一个对象不同,则将该字段放入返回对象中.

It's not too hard to create a function like this. Just loop through each field in the second object, and if it's not present in the first or the value is different than the first, put that field in the return object.

var compareJSON = function(obj1, obj2) {
  var ret = {};
  for(var i in obj2) {
    if(!obj1.hasOwnProperty(i) || obj2[i] !== obj1[i]) {
      ret[i] = obj2[i];
    }
  }
  return ret;
};

您可以在此演示页面上看到它的运行情况.

这篇关于Javascript JSON比较/差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆