【问题标题】:jQuery Comparing and find out the difference between 2 json arrayjQuery比较并找出2个json数组之间的区别
【发布时间】:2013-11-20 10:59:35
【问题描述】:

我有 2 个如下的 json 数组,稍后我会做一个 jQuery 扩展。我想使用 jQuery 并仅将 array1 中的所有元素 (a,b) 与 array2 进行比较,以检查 (a,b) 是否存在于 array2 中,如果存在则获取差异。

我已经尝试过如下代码,但不知何故,我总是得到意外的控制台输出作为下面的实际返回。如果您有任何建议,我将不胜感激。

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

预期回报:

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

实际回报:

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

【问题讨论】:

标签: jquery arrays json


【解决方案1】:

我已参考下面的链接并相应地修改给定的答案。修改后的答案如下。

参考资料: Compare two JSON arrays in JQuery or Javascript

修改答案:

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

实际回报:

Object {b: "1002"} 

【讨论】:

    猜你喜欢
    • 2019-01-23
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    相关资源
    最近更新 更多