如何根据第二个数组中的值从JS数组中删除对象

时间:2014-07-02 18:42:13

标签: javascript jquery arrays

嘿伙计们我正在尝试从数组中删除与第二个数组中的值匹配的所有对象。请允许我用一些例子来解释一下!

var originalObj = [
{"id":"88","name":"Lets go testing"},
{"id":"88","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"},
{"id":"99","name":"Have fun boys and girls2"},
{"id":"108","name":"You are awesome!"}
]

目前使用我的javascript代码,我只能删除对象中的一个指定值以及具有所述值的任何出现

var updatedObj= $.grep(originalObj , function(e){ 
             return e.id!= '88'; 
        });

console.log(updatedObj)
[
    {"id":"108","name":"You are awesome!"},
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"},
    {"id":"99","name":"Have fun boys and girls2"},
    {"id":"108","name":"You are awesome!"}
]

我想要完成的是让.grep函数查找第二个看起来像这样的数组。

 var filterID = ["88","99"];

所以结果看起来应该是这样的

//Needs updating
//var updatedObj= $.grep(originalObj , function(e){ 
//           return e.id!= '88'; <-- needs to match all filterID values instead
//      });

console.log(updatedObj)
[
    {"id":"108","name":"You are awesome!"},
    {"id":"108","name":"You are awesome!"},
    {"id":"108","name":"You are awesome!"}
]

非常感谢任何帮助!

谢谢。

4 个答案:

答案 0 :(得分:2)

您可以迭代数组中的所有值并以此方式进行过滤。

var updatedObj = originalObj;
for (var i in filterID) {
  updatedObj = $.grep(updatedObj , function(e){ 
    return e.id!= filterID[i];
  });
}

答案 1 :(得分:2)

如果使用对象来表示要过滤的键列表,则这变得很简单:

var toRemove = {
    88: true, 99: true;  // keys significant, values thereof irrelevant
};

var updatedObj = $.grep(originalObj, function(e) { 
    return !(e.id in toRemove);
});

对于短数组,这与双嵌套循环的效率大致相同,约为O(n * m),其中n是被过滤数组的大小,m是要删除的元素数量。)

但是,如果要过滤的值数组很大,那么这将是O(n)(假设in运算符在恒定时间内执行)

答案 2 :(得分:0)

使用indexOf数组函数

var filterID = ["88","99"];
var updatedObj= $.grep(originalObj , function(e){ 
    return filterID.indexOf(e.id) === -1; 
});

答案 3 :(得分:0)

您可以迭代数组中的所有值并以此方式进行过滤。

           var updatedObj = [
                {"id":"108","name":"You are awesome!"},
                {"id":"99","name":"Have fun boys and girls"},
                {"id":"108","name":"You are awesome!"},
                {"id":"99","name":"Have fun boys and girls2"},
                {"id":"108","name":"You are awesome!"}
            ],
            filterId = ["89","99"],result=[];
            $.each(updatedObj,function(index,item){
                if(filterId.indexOf(item.id) === -1){
                   result.push(updatedObj[index])
                }
            })
            console.log(result);