比较json对象数组中的值

时间:2018-09-19 18:58:58

标签: javascript javascript-objects

我有一个json array1作为:

[
 { id:0, name:"adam", uName: "aSilver", uId: "123", table: "table1"},
 { id:1, name:"john", uName: "jBerlin", uId: "456", table: "table1"}
]

我还有另一个json array2:

[
 { id:0, name:"adam", uName: "aSilver, jBerlin", uId: "123, 456", createdBy: 
"auto", createdOn: "09/10/2018", desc: "none", table: "table1"},
 { id:1, name:"john", uName: "aSilver, jBerlin", uId: "123, 456", createdBy: 
"auto", createdOn: "09/10/2018", desc: "none1", table: "table1"},
 { id:0, name:"steve" uName: "aSilver, jBerlin, pParis", uId: "123, 456, 
 789", createdBy: "auto", createdOn: "09/10/2018", desc: "none2", table: 
"table2"},
 { id:0, name:"nash", uName: "aSilver, jBerlin, pParis", uId: "123, 456, 
 789", createdBy: "auto", createdOn: "09/10/2018", desc: "none3", table: 
"table2"},
 { id:0, name:"sand", uName: "aSilver", uId: "123", createdBy: "auto", 
createdOn: "09/10/2018", desc: "none4", table: "table3"}
]

我必须检查array2中是否存在uname + uid的组合

如下所示:

首先必须从array2获得唯一值。唯一值基于“表”键。结果如下:

[
 { id:0, name:"adam", uName: "aSilver, jBerlin", uId: "123, 456", createdBy: 
"auto", createdOn: "09/10/2018", desc: "none", table: "table1"},
 { id:0, name:"steve" uName: "aSilver, jBerlin, pParis", uId: "123, 456, 
789", createdBy: "auto", createdOn: "09/10/2018", desc: "none2", table: 
"table2"},
 { id:0, name:"sand", uName: "aSilver", uId: "123", createdBy: "auto", 
createdOn: "09/10/2018", desc: "none4", table: "table3"}
]

现在我可以遍历上面的数组,创建新的json array3:

[
 { comparer: "aSilver_123, jBerlin_456", table: "table1" }
 { comparer: "aSilver_456, jBerlin_456, pParis_789", table: "table 2" }
 { comparer: "aSilver_123", table: "table 3" }
]

现在我只需要比较array1和array3比较器键

由于array1具有“ aSilver_123,jBerlin_456”,与array3的第一项相似。我现在抛出一个错误,即“ table1”具有重复的值。

就目前而言,我发现了以下检查唯一性的方法,但是我必须在对象数组中找到唯一性,因此这将无法工作。

     Array.prototype.unique = function () {
        var r = new Array();
        o: for (var i = 0, n = this.length; i < n; i++) {
            for (var x = 0, y = r.length; x < y; x++) {
                if (r[x] == this[i]) {                       
                    return false;
                }
            }
            r[r.length] = this[i];
        }
        return true;
    }

对不起,我知道我要寻找的它有点不寻常。

想知道什么有效的方法来解决这个问题?

谢谢

这是我的jsfiddle

http://jsfiddle.net/50pxjkda/7

1 个答案:

答案 0 :(得分:1)

创建一个对象,其键为table的{​​{1}}属性。由于对象键是唯一的,因此可以为您提供唯一的对象。

array2

要查找obj = {}; array2.forEach(o => obj[o.table] = o); unique_array2 = Object.keys(obj).map(k => obj[k]); array1共有的元素,您只需使用比较属性的嵌套循环即可。

unique_array2