G-M*_*Man 26 javascript arrays jquery
我有以下数组
var countries = {};
countries.results = [
    {id:'AF',name:'Afghanistan'},
    {id:'AL',name:'Albania'},
    {id:'DZ',name:'Algeria'}
];
如何使用其名称或ID从此数组中删除项?
谢谢
Joh*_*ler 52
为此创造了一个方便的功能..
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');
Roc*_*mat 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');
c-s*_*ile 20
试试这个:
var COUNTRY_ID = 'AL';
countries.results = 
  countries.results.filter(function(el){ return el.id != COUNTRY_ID; });
| 归档时间: | 
 | 
| 查看次数: | 116185 次 | 
| 最近记录: |