比较JSON对象数组中的值

2022-08-06 00:00:00 javascript javascript-objects

我有一个json数组1为:

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

我有另一个json array2 AS:

[
 { 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"}
]

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

如下:

从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比较器键

由于数组1具有类似于数组3的第一项的"aSilver_123,j柏林_456"。我现在会抛出一个错误,即"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


解决方案

创建以array2table属性为键的对象。由于对象键是唯一的,因此这将为您获取唯一的对象。

obj = {};
array2.forEach(o => obj[o.table] = o);
unique_array2 = Object.keys(obj).map(k => obj[k]);

若要查找array1unique_array2共有的元素,只需使用比较属性的嵌套循环。

matches = [];
array1.forEach(o1 => unique_array2.forEach(o2 => {
    if (o1.uName == o2.uName && o1.uid == o2.uid) {
        matches.push(o1);
    }
}));

相关文章