26

I have the following array

var countries = {};

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

How can I remove an item from this array using its name or id ?

Thank you

Felix Kling
  • 705,106
  • 160
  • 1,004
  • 1,072
G-Man
  • 6,807
  • 18
  • 65
  • 94

10 Answers10

53

Created a handy function for this..

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');
John Strickler
  • 23,772
  • 4
  • 49
  • 67
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');
Rocket Hazmat
  • 204,503
  • 39
  • 283
  • 323
  • 3
    +1: This isn't the highest voted answer, but it worked best for me. I was parsing a JSON array that I was getting back from a jquery AJAX success handler, and the $.each method was unexpectedly tripping over 'undefined' values. I'm still not sure why I was getting back 'undefined' values to begin with; but in any event, this code snippet definitely worked best for me. Thanks! – Jim G. May 30 '12 at 21:33
  • @JimG.: Glad I could be of help :-) – Rocket Hazmat May 30 '12 at 21:55
  • 1
    @JimG The undefined values you get are because the indexes changed after the array elements have been spliced out, so the accepted answer doesn't actually work. Can you change it to this one] – theringostarrs Oct 23 '12 at 22:11
  • 1
    @GX.: Can you please change the accepted answer to this answer? – Jim G. Oct 23 '12 at 22:36
  • 2
    Just a heads up, if the value of the property of the JSON object you're deleting is a number(like: `{"key": 1}`), make sure you cast the parameter you're passing into the function to a number: `removeValue('key', +value);` this drove me nuts for a couple of hours. – Mohammad Sepahvand Sep 10 '13 at 11:31
21

Try this:

var COUNTRY_ID = 'AL';

countries.results = 
  countries.results.filter(function(el){ return el.id != COUNTRY_ID; });
c-smile
  • 24,546
  • 7
  • 54
  • 79
  • 5
    +1: Worth noting that it [isn't supported in IE < 9](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter#Browser_compatibility) – Jeremy Jun 10 '11 at 18:53
  • @Jeremy Heiler: for IE such function can be added from code provided here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter – c-smile Jun 10 '11 at 18:56
  • 4
    You referenced the same link I referenced :-P – Jeremy Jun 10 '11 at 18:57
2

Try this.(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"]);
ScottLee
  • 55
  • 2
  • 8
1

You can delete by 1 or more properties:

//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;
}
NDB Sites
  • 9
  • 4
0

This that only requires javascript and appears a little more readable than other answers. (I assume when you write 'value' you mean 'id')

//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);
}
KXL
  • 335
  • 3
  • 6
  • Delete should only be used for removing properties from objects, NOT for deleting things in an array - it merely replaces the value at that index with undefined! (Does not change length of array, etc). See http://stackoverflow.com/questions/5767325/remove-a-particular-element-from-an-array-in-javascript#comment20295018_5767335 – Aaron_H Nov 05 '15 at 04:08
0

it worked for me..

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

You can do it with _.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>
Penny Liu
  • 7,720
  • 5
  • 40
  • 66
0

Maybe this is helpful, too.

for (var i = countries.length - 1; i--;) {
    if (countries[i]['id'] === 'AF' || countries[i]['name'] === 'Algeria'{
        countries.splice(i, 1);
    }
}
Muzaffer Galata
  • 480
  • 1
  • 5
  • 14
0

you can use delete operator to delete property by it's name

delete objectExpression.property

or iterate through the object and find the value you need and delete it:

for(prop in Obj){
   if(Obj.hasOwnProperty(prop)){
      if(Obj[prop] === 'myValue'){
        delete Obj[prop];
      }
   }
}
Headshota
  • 19,673
  • 11
  • 54
  • 77