Javascript JSON比较/差异?

编程入门 行业动态 更新时间:2024-10-24 01:51:25
本文介绍了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比较/差异?

本文发布于:2023-10-24 14:46:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524215.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:差异   Javascript   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!