jQuery的比较,找出2 JSON数组之间的区别 [英] jQuery Comparing and find out the difference between 2 json array

查看:472
本文介绍了jQuery的比较,找出2 JSON数组之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个JSON数组作为下面,我会做一个jQuery的扩展以后。我想使用jQuery而仅比较所有元素(A,B)从对数组2数组1,检查是否(A,B)存在于数组2,如果存在,获得的区别。

我曾尝试code如下但不知何故,我总是得到意想不到的控制台输出如下实际收益。我想任何意见AP preciate。

  VAR数组1 = {A:AT,B:1000};
VAR数组2 = {C:0,D:100,AT,B:1002};
的console.log($(数组1)。不是(数组2)获得());

预期回报率:

  [对象]
    0:对象
    B:1000
    __proto__:对象
    长度:1
    __proto__:数组[0]

实际回报:

  [对象]
    0:对象
    答:AT
    B:1000
    __proto__:对象
    长度:1
    __proto__:数组[0]


解决方案

我已经请参阅下面的链接,并相应修改给出答案。修改后的答案如下。

参考:
<一href=\"http://stackoverflow.com/questions/12160998/compare-two-json-arrays-in-jquery-or-javascript\">Compare在JQuery的或JavaScript 2 JSON阵列

修改答案:

  VAR origArrayGroups = {C:0,D:100,AT,B:1002};
VAR userArrayGroups = {A:AT,B:1000};变种的diff = {};
对(在userArrayGroups VAR道具){
    的console.log(比较元素:+道具);
    如果(userArrayGroups [道具]!= origArrayGroups [道具])
    {
        差异[道具] = origArrayGroups [道具]
        的console.log(结果:!=+ userArrayGroups [道具] + + origArrayGroups [道具]);
    }
    其他
    {的console.log(结果:+ userArrayGroups [道具] +==+ origArrayGroups [道具]);}}的console.log(差异);

实际回报率:

 对象{B:1002}

I have 2 json arrays as below and I will do an jQuery extend later. I would like to use jQuery and compare only all elements (a,b) from array1 against array2, to check whether the (a,b) exists in array2 and get the difference if exists.

I have tried the code as below but somehow I always got the unexpected console output as actual return below. I would appreciate for any advice.

var array1 = {a: "AT", b: "1000"};
var array2 = {c: 0, d: 100, a: "AT", b: "1002"};
console.log($(array1).not(array2).get());

Expected return:

[Object]
    0: Object
    b: "1000"
    __proto__: Object
    length: 1
    __proto__: Array[0]

Actual return:

[Object]
    0: Object
    a: "AT"
    b: "1000"
    __proto__: Object
    length: 1
    __proto__: Array[0]

解决方案

I have refer to the link below and modify the given answer accordingly. The modified answer as below.

References: Compare two JSON arrays in JQuery or Javascript

Modified Answer:

var origArrayGroups = {c: 0, d: 100, a: "AT", b: "1002"};
var userArrayGroups = {a: "AT", b: "1000"};

var diff = {};
for (var prop in userArrayGroups) {
    console.log("Comparing element: " + prop);
    if(userArrayGroups[prop] != origArrayGroups[prop])
    {
        diff[prop] = origArrayGroups[prop];
        console.log("Result: " + userArrayGroups[prop] + "!=" + origArrayGroups[prop]);
    }
    else
    {console.log("Result: " + userArrayGroups[prop] + "==" + origArrayGroups[prop]);}

}

console.log(diff);

Actual Return:

Object {b: "1002"} 

这篇关于jQuery的比较,找出2 JSON数组之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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