web-dev-qa-db-fra.com

supprimer un élément du tableau en utilisant son nom/valeur

J'ai le tableau suivant 

var countries = {};

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

Comment puis-je supprimer un élément de ce tableau en utilisant son nom ou son identifiant?

Je vous remercie

25
G-Man
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');
35
Rocket Hazmat

Créé une fonction pratique pour cela ..

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');
51
John Strickler

Essaye ça:

var COUNTRY_ID = 'AL';

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

Essayez ceci. (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"]);
2
ScottLee

Vous pouvez supprimer 1 ou plusieurs propriétés:

//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;
}
1
NDB Sites

Vous pouvez le faire avec _.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>

0
Yi-Ting Liu

vous pouvez utiliser l'opérateur delete pour supprimer une propriété par son nom

delete objectExpression.property

ou parcourez l'objet pour trouver la valeur dont vous avez besoin et supprimez-le:

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

Cela ne nécessite que javascript et semble un peu plus lisible que d’autres réponses ..__

//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);
}
0
KXL

cela a fonctionné pour moi ..

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