What I want to do is to remove a set of objects from my original array of objects in angularjs.
I have this set of array of objects:
var obj = [{
id: 1,
name: "Ben",
role: [{
roleId: 1,
roleName: role01
},
{
roleId: 2,
roleName: role02
}]
},
{
id: 2,
name: "Anna",
role: [{
roleId: 3,
roleName: role03
},
{
roleId: 4,
roleName: role04
}]
},
{
id: 3,
name: "Dan",
role: [{
roleId: 3,
roleName: role03
},
{
roleId: 4,
roleName: role04
}]
},
{
id: 4,
name: "Matt",
role: [{
roleId: 1,
roleName: role01
},
{
roleId: 2,
roleName: role02
}]
}];
And I want to remove these elements from the array above:
var removeObj = [{
id: 3,
name: "Dan",
role: [{
roleId: 3,
roleName: role03
},
{
roleId: 4,
roleName: role04
}]
},
{
id: 4,
name: "Matt",
role: [{
roleId: 1,
roleName: role01
},
{
roleId: 2,
roleName: role02
}]
}];
Is this solution possible?
PS What I have done is to use 'splice' but it only removes one element at a time. Can splice also removes a set of elements inside an object?
obj.splice(index, 1);
//Solution 1 using filter
let removeArray = removeObj.map(function(item){
return item.id;
});
let result1 = obj.filter(function(item){
return !removeArray.includes(item.id);
});
console.log(result1);
//Solution 2 using slice
//Considered it's valid just if obj is ordered by id and removeObj too.
let result2 = obj.slice(0,removeObj.length);
console.log(result2);
If you consider usage of 3rd party library to simplify that, I will recommend you lodash: https://lodash.com .
It provides serious amount of methods to work with collections. This is the one you need in your case. Simply do _.difference(obj, removeObj)
and let the library do everything for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.