我有一个带有两个参数ml_successor和ml_predecessor的对象, 如果这些参数都匹配,我想从对象中删除重复项。
下面是我尝试的代码,但即使其中一个参数(ml_successor或ml_predecessor)与其他项匹配,也会删除项目。
var depArr = [{
"ml_predecessor": "0e1cea11-4af4-4bb9-9269-8a1eecc3e848",
"ml_successor": "c67c5b33-8e5c-48fc-9178-50eb8379426c"
}, {
"ml_predecessor": "0e1cea11-4af4-4bb9-9269-8a1eecc3e848",
"ml_successor": "db1cfd99-1e07-47b7-b9e0-bb84420f454e"
}, {
"ml_predecessor": "0e1cea11-4af4-4bb9-9269-8a1eecc3e848",
"ml_successor": "c67c5b33-8e5c-48fc-9178-50eb8379426c"
}, {
"ml_predecessor": "db1cfd99-1e07-47b7-b9e0-bb84420f454e",
"ml_successor": "73133d97-b094-41dd-ba2c-c93502a68bfa"
}, {
"ml_predecessor": "0e1cea11-4af4-4bb9-9269-8a1eecc3e848",
"ml_successor": "db1cfd99-1e07-47b7-b9e0-bb84420f454e"
}, {
"ml_predecessor": "db1cfd99-1e07-47b7-b9e0-bb84420f454e",
"ml_successor": "73133d97-b094-41dd-ba2c-c93502a68bfa"
}];
var dupes = {},
dupes1 = {},
singles = [];
$.each(depArr, function(i, el) {
if (!dupes[el.ml_predecessor] && !dupes1[el.ml_successor]) {
dupes[el.ml_predecessor] = true;
dupes1[el.ml_successor] = true;
singles.push(el);
}
});
答案 0 :(得分:0)
使用此:
const singles = [];
const inArray = (array, item) => {
return $.grep(array, (arrayItem) => {
return arrayItem.ml_predecessor === item.ml_predecessor && arrayItem.ml_successor === item.ml_successor;
}).length > 0;
};
$.each(depArr, (index, item) => {
if (!inArray(singles, item)) {
singles.push(item);
}
});