如何在JavaScript中基于关联记录从数组中删除重复对象



我必须有一个数组,一个是users,另一个assignmentsusers是多维数组,就像下面的一样

users = [
{id: 1, name: 'john'},
{id: 2, name: 'john'},
{
id: 3,
name: 'john', 
assignments: [
{id: 1, userId: 3, postId: 2}
]
},  
]
assignments = [
{id: 1, userId: 3, postId: 2}
]

我试过

const usersIDs = new Set(users.map(({ id }) => id))
const combined = [
...users,
...assignments.filter(({ userId }) => !usersIDs.has(userId))
]

我想从id&CCD_ 5与CCD_ 6表匹配。

我尝试过几种方法,在谷歌上找到,但运气不好。

我现在该怎么办?我怎样才能做到这一点?

感谢

请使用以下代码获取输出

assignments.forEach(asgn => {
if (users.some(user => user.id === asgn.postId)) {
const index = users.findIndex(user => user.id === asgn.postId);
users.splice(index, 1);
}
});
console.log(users);

这应该对您有效。

const users = [
{ id: 1, name: 'john' },
{ id: 2, name: 'john' },
{
id: 3, name: 'john',
assignments: [
{ id: 1, userId: 3, postId: 2 }
]
},
]
const assignments = [
{ id: 1, userId: 3, postId: 2 }
]

assignments.forEach(assignment => {
const index = users.findIndex(
user => user.assignments ? user.assignments.findIndex(a => a.id === assignment.id && a.userId === assignment.userId && a.postId === assignment.postId) : -1);
if (index > -1) {
users.splice(index, 1);
}
});
console.log(users);

请尝试此代码,希望它能为您工作。

users = [
{id: 1, name: 'john'},
{id: 2, name: 'john'},
{id: 3, name: 'john',
assignments: [
{id: 1, userId: 3, postId: 2}
]
},   
]
assignments = [
{id: 1, userId: 3, postId: 2}
]
users.forEach(matchValueFunction);
function matchValueFunction(item,index) {   
if(item.assignments){
for(var i=0; i< assignments.length; i++){
if(item.assignments[0].id == assignments[i].id && item.assignments[0].postId == assignments[i].postId){
users.splice(index);
}
}
}
}
console.log(users);

相关内容

  • 没有找到相关文章