使用其名称/值从数组中删除项目

时间:2011-06-10 18:34:46

标签: javascript jquery arrays

我有以下数组

var countries = {};

countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];

如何使用其名称或ID从此数组中删除项目?

谢谢

10 个答案:

答案 0 :(得分:51)

为此创建了一个方便的功能..

function findAndRemove(array, property, value) {
  array.forEach(function(result, index) {
    if(result[property] === value) {
      //Remove from array
      array.splice(index, 1);
    }    
  });
}

//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');

答案 1 :(得分:35)

Array.prototype.removeValue = function(name, value){
   var array = $.map(this, function(v,i){
      return v[name] === value ? null : v;
   });
   this.length = 0; //clear original array
   this.push.apply(this, array); //push all elements except the one we want to delete
}

countries.results.removeValue('name', 'Albania');

答案 2 :(得分:18)

试试这个:

var COUNTRY_ID = 'AL';

countries.results = 
  countries.results.filter(function(el){ return el.id != COUNTRY_ID; });

答案 3 :(得分:2)

试试这个。(IE8 +)

//Define function
function removeJsonAttrs(json,attrs){
    return JSON.parse(JSON.stringify(json,function(k,v){
        return attrs.indexOf(k)!==-1 ? undefined: v;
}));}
//use object
var countries = {};
countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
countries = removeJsonAttrs(countries,["name"]);
//use array
var arr = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
arr = removeJsonAttrs(arr,["name"]);

答案 4 :(得分:1)

您可以删除1个或多个属性:

//Delets an json object from array by given object properties. 
//Exp. someJasonCollection.deleteWhereMatches({ l: 1039, v: '3' }); -> 
//removes all items        with property l=1039 and property v='3'.
Array.prototype.deleteWhereMatches = function (matchObj) {
    var indexes = this.findIndexes(matchObj).sort(function (a, b) { return b > a; });
    var deleted = 0;
    for (var i = 0, count = indexes.length; i < count; i++) {
        this.splice(indexes[i], 1);
        deleted++;
    }
    return deleted;
}

答案 5 :(得分:0)

您可以使用删除操作符来删除属性名称

delete objectExpression.property

或遍历对象并找到所需的值并将其删除:

for(prop in Obj){
   if(Obj.hasOwnProperty(prop)){
      if(Obj[prop] === 'myValue'){
        delete Obj[prop];
      }
   }
}

答案 6 :(得分:0)

这只需要javascript,并且看起来比其他答案更具可读性。 (我假设当你写“价值&#39;你的意思是&#39; id&#39;)

//your code
var countries = {};

countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
// solution:
//function to remove a value from the json array
function removeItem(obj, prop, val) {
    var c, found=false;
    for(c in obj) {
        if(obj[c][prop] == val) {
            found=true;
            break;
        }
    }
    if(found){
        delete obj[c];
    }
}
//example: call the 'remove' function to remove an item by id.
removeItem(countries.results,'id','AF');

//example2: call the 'remove' function to remove an item by name.
removeItem(countries.results,'name','Albania');

// print our result to console to check it works !
for(c in countries.results) {
    console.log(countries.results[c].id);
}

答案 7 :(得分:0)

它对我有用..

countries.results= $.grep(countries.results, function (e) { 
      if(e.id!= currentID) {
       return true; 
      }
     });

答案 8 :(得分:0)

您可以通过 _.pullAllBy 来实现。

var countries = {};

countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];

// Remove element by id
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');

// Remove element by name
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');
console.log(countries);
.as-console-wrapper {
  max-height: 100% !important;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

答案 9 :(得分:0)

也许这也很有帮助。

for (var i = countries.length - 1; i--;) {
    if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
        countries.splice(i, 1);
    }
}