从对象数组中删除某些对象

时间:2017-11-08 02:02:40

标签: javascript angularjs

我想要做的是从angularjs中的原始对象数组中删除一组对象。

我有这组对象:

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
    }]
}];

我想从上面的数组中删除这些元素:

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
    }]
}];

这个解决方案可行吗?

P.S。我所做的是使用'splice',但它一次只删除一个元素。拼接还可以删除对象内的一组元素吗?

obj.splice(index, 1);

2 个答案:

答案 0 :(得分:3)

//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);

答案 1 :(得分:0)

如果你考虑使用第三方库来简化它,我会建议你lodash:https://lodash.com

它提供了大量使用集合的方法。这是您需要的。只需做_.difference(obj, removeObj),让图书馆为您做一切。

https://lodash.com/docs/4.17.4#difference