简体   繁体   English

按值从数组中删除项目

[英]Remove an item from an array by value

I have an array of items like:我有一系列项目,例如:

var items = [id: "animal", type: "cat", cute: "yes"]

And I'm trying to remove any items that match the ID given.我正在尝试删除与给定 ID 匹配的所有项目。 In this case;在这种情况下; animal

I'm stuck!我被卡住了! I can get it to work easily by having a more simpler array but this is not what I need... I also need to remove the item by value as I don't want the hassle of referring to items by their index.通过使用更简单的数组,我可以让它轻松工作,但这不是我需要的......我还需要按值删除项目,因为我不希望通过索引引用项目的麻烦。

Is there a jQuery method I could use where I don't need to iterate through the items array, rather specify a selector?有没有我可以使用的 jQuery 方法,我不需要遍历 items 数组,而是指定一个选择器?

Here is my jsFiddle: http://jsfiddle.net/zafrX/这是我的 jsFiddle: http : //jsfiddle.net/zafrX/

I'm not sure how much of a hassle it is to refer to array items by index.我不确定按索引引用数组项有多少麻烦。 The standard way to remove array items is with the splice method删除数组项的标准方法是使用splice 方法

for (var i = 0; i < items.length; i++)
    if (items[i] === "animal") { 
        items.splice(i, 1);
        break;
    }

And of course you can generalize this into a helper function so you don't have to duplicate this everywhere.当然,您可以将其概括为辅助函数,这样您就不必在任何地方复制它。


EDIT编辑

I just noticed this incorrect syntax:我刚刚注意到这个不正确的语法:

var items = [id: "animal", type: "cat", cute: "yes"]

Did you want something like this:你想要这样的东西:

 var items = [ {id: "animal",  type: "cat", cute: "yes"}, {id: "mouse",  type: "rodent", cute: "no"}];

That would change the removal code to this:这会将删除代码更改为:

for (var i = 0; i < items.length; i++)
    if (items[i].id && items[i].id === "animal") { 
        items.splice(i, 1);
        break;
    }

No need for jQuery or any third party lib for this, now we can use the new ES5 filter :不需要 jQuery 或任何第三方库,现在我们可以使用新的 ES5 过滤器:

let myArray = [{ id : 'a1', name : 'Rabbit'}, { id : 'a2', name : 'Cat'}];
myArray = myArray.filter(i => i.id !== 'a1');

You can either use splice or run a delete yourself.您可以使用splice或自己运行删除。 Here's an example:下面是一个例子:

for (var i = 0; i < items.length; i ++) {
    if (items[i] == "animal") { 
        items.splice(i, 1);
        break;
    }
}

There's a simple way!有一个简单的方法!

myItems.splice(myItems.indexOf(myItems.find(row => row.id == id)), 1);

Demo below:演示如下:

 // define function function delete_by_id(id) { var myItems = [{ id: 1, type: "cat", cute: "yes" }, { id: 2, type: "rat", cute: "yes" }, { id: 3, type: "mouse", cute: "yes" }]; // before console.log(myItems); myItems.splice(myItems.indexOf(myItems.find(item => item.id == id)), 1); // after console.log(myItems); } // call function delete_by_id(1);

You should do it like this (make sure that you have the right syntax...you cannot have array with properties, but object inside {} and then you can iterate by keys and delete unwanted key):你应该这样做(确保你有正确的语法......你不能有带属性的数组,但对象在{} ,然后你可以通过键进行迭代并删除不需要的键):

var items = {id: "animal", type: "cat", cute: "yes"}
var removeItem = "animal"; // or with the ID matching animal...

for(var p in items){
    if(items[p] === removeItem)
        delete items[p]
}

And to answer you question, you cannot apply jquery selectors to javascript objects.为了回答您的问题,您不能将 jquery 选择器应用于 javascript 对象。 The best you can do to avoid for loop is to use $.each (which is a loop written in a more "functional" way).避免for循环的最佳方法是使用$.each (这是一个以更“功能”的方式编写的循环)。

By using object notation : http://jsfiddle.net/jrm2k6/zafrX/2/通过使用对象表示法: http : //jsfiddle.net/jrm2k6/zafrX/2/

var animal1 = {id: "animal", type: "cat", cute: "yes"}
var car2 = {id: "car", type: "pick-up", cute: "no"}
var animal3 = {id: "animal", type: "dog", cute: "yes"}
var removeItem = "animal"; // or with the ID matching animal...

var array_items = []
array_items.push(animal1);
array_items.push(car2);
array_items.push(animal3);

for(var i=0;i<array_items.length;i++){
    if(array_items[i].id == removeItem){
        array_items.splice(i,1);
    }
}

//alert(array_items.length);  

Wow, so many ideas but still not what I wanted xD哇,这么多想法,但仍然不是我想要的 xD

This will remove ALL entries of the given value and return the removed value:这将删除给定值的所有条目并返回删除的值:

function removeOfArray(val, arr){
    var idx;
    var ret;
    while ((idx = arr.indexOf(val)) > -1){
        arr.splice(idx, 1);
        ret = val;
    }
    return ret;
}

Also I found other solutions here: Remove item from array by value我还在这里找到了其他解决方案: 按值从数组中删除项目

-parray : list of array of object
-pstring :value to remove from the array
-ptag :using which tag we

 function removeFromArr (parray,ptag,pstring){ var b =[]; var count = 0; for (var i =0;i<parray.length;i++){ if(pstring != parray[i][ptag]){ b[count] = parray[i]; count++; } } return b; } var lobj = [ { "SCHEME_CODE": "MIP65", "YEARS": "1", "CURRENCY": "GBP", "MAX_AMT": 200000, "MIN_AMT": 1000, "AER_IR": "1.80", "FREQUENCY": "Monthly", "CUST_TYPE": "RETAIL", "GROSS_IR": "1.79" }, { "SCHEME_CODE": "MIP65", "YEARS": "2", "CURRENCY": "GBP", "MAX_AMT": 200000, "MIN_AMT": 1000, "AER_IR": "1.98", "FREQUENCY": "Monthly", "CUST_TYPE": "RETAIL", "GROSS_IR": "1.96" }, { "SCHEME_CODE": "MIP65", "YEARS": "3", "CURRENCY": "GBP", "MAX_AMT": 200000, "MIN_AMT": 1000, "AER_IR": "2.05", "FREQUENCY": "Monthly", "CUST_TYPE": "RETAIL", "GROSS_IR": "2.03" }, { "SCHEME_CODE": "MIP65", "YEARS": "5", "CURRENCY": "GBP", "MAX_AMT": 200000, "MIN_AMT": 1000, "AER_IR": "2.26", "FREQUENCY": "Monthly", "CUST_TYPE": "RETAIL", "GROSS_IR": "2.24" }, { "SCHEME_CODE": "QIP65", "YEARS": "1", "CURRENCY": "GBP", "MAX_AMT": 200000, "MIN_AMT": 1000, "AER_IR": "1.80", "FREQUENCY": "Quarterly", "CUST_TYPE": "RETAIL", "GROSS_IR": "1.79" }, { "SCHEME_CODE": "QIP65", "YEARS": "2", "CURRENCY": "GBP", "MAX_AMT": 200000, "MIN_AMT": 1000, "AER_IR": "1.98", "FREQUENCY": "Quarterly", "CUST_TYPE": "RETAIL", "GROSS_IR": "1.97" }, ] function myFunction(){ var final = removeFromArr(lobj,"SCHEME_CODE","MIP65"); console.log(final); }
 <html> <button onclick="myFunction()">Click me</button> </html>

are going to remove from the objects将从对象中删除

function removeFromArr(parray, pstring, ptag) {
        var farr = [];
        var count = 0;
        for (var i = 0; i < pa.length; i++) {
            if (pstring != pa[i][ptag]) {
                farr[count] = pa[i];
                count++;
            }
        }
        return farr;
    }

ES6 解决方案

persons.splice(persons.findIndex((pm) => pm.id === personToDelete.id), 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM