简体   繁体   English

从Javascript中的对象数组中删除选定的项目

[英]Remove selected items from array of object in Javascript

I have one array of object from which i have to remove selected object and create new array of object. 我有一个对象数组,必须从中删除所选对象并创建对象的新数组。

//Get all items from 'Product' dropdown
var allItems = [{ text: "India", value: "10" }, { text: "Canada", value: "12" }, { text: "US", value: "17" }, { text: "Austria", value: "18" }, { text: "South Africa", value: "14" }];

var itemsToRemove = ["17", "10"];

var newItems = [{ text: "Canada", value: "12" }, { text: "Austria", value: "18" }, { text: "South Africa", value: "14" }];

Use Array.prototype.filter : 使用Array.prototype.filter

var newItems = allItems.filter(function(e) {
    // A.indexOf(x) == -1 if x is not found in A
    return itemsToRemove.indexOf(e.value) === -1;
});

 var allItems = [ { text: "India", value: "10" }, { text: "Canada", value: "12" }, { text: "US", value: "17" }, { text: "Austria", value: "18" }, { text: "South Africa", value: "14" } ]; var itemsToRemove = ["17", "10"]; var newItems = allItems.filter(function(e) { return itemsToRemove.indexOf(e.value) === -1; }); console.log( newItems ); 

You can simply use splice for properly deleting and indexing javascript array. 您可以简单地使用splice正确删除和索引javascript数组。

 var allItems = [{ text: "India", value: "10" }, { text: "Canada", value: "12" }, { text: "US", value: "17" }, { text: "Austria", value: "18" }, { text: "South Africa", value: "14" }]; var itemsToRemove = ["17", "10"]; for (var i = 0; i < allItems.length; i++) { for (var j = 0; j < itemsToRemove.length; j++) { if (allItems[i].value == itemsToRemove[j]) allItems.splice(i, 1); } } 

Try It. 试试吧。

var allItems = [{
      text: "India",
      value: "10"
    }, {
      text: "Canada",
      value: "12"
    }, {
      text: "US",
      value: "17"
    }, {
      text: "Austria",
      value: "18"
    }, {
      text: "South Africa",
      value: "14"
    }];

    var itemsToRemove = ["17", "10"];

    for (var i = 0; i < allItems.length; i++) {
        if(itemsToRemove.indexOf(allItems[i].value) >= 0) {
            allItems.splice(i, 1);
        }
    }   

Thanks everybody for you answers, this is how i solved it. 谢谢大家的回答,这就是我解决的方法。

var newItems = allItems.filter(function(item) {
    for (var i = 0; i < itemsToRemove.length; i++)
       if (itemsToRemove[i] == item.value) return false;
    return true;
});

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

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