27

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

11 Answers 11

54

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');
5
  • 10
    Note: jQuery is necessary to use this function
    – Headshota
    Jun 10, 2011 at 18:53
  • 7
    Does this not break the index, because the index changes during execution if an element is removed.
    – Alex
    Mar 15, 2012 at 14:55
  • @JohnStrickler: can you rewrite this without jquery please. I don't like librairies.
    – Mimouni
    May 17, 2014 at 22:27
  • According to the documentation api.jquery.com/each, $.each doesn't take two arguments (anymore?).
    – KVM
    Jul 2, 2014 at 14:20
  • Thanks. Works like a charm :-)
    – Karan
    Sep 12, 2016 at 14:13
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');
5
  • 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, 2012 at 21:33
  • @JimG.: Glad I could be of help :-)
    – gen_Eric
    May 30, 2012 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] Oct 23, 2012 at 22:11
  • 1
    @GX.: Can you please change the accepted answer to this answer?
    – Jim G.
    Oct 23, 2012 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. Sep 10, 2013 at 11:31
22

Try this:

var COUNTRY_ID = 'AL';

countries.results = 
  countries.results.filter(function(el){ return el.id != COUNTRY_ID; });
3
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"]);
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;
}
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];
      }
   }
}
1
  • 4
    I think he wants to delete the entire object from the array. Instead of deleting the property from the object. Jun 10, 2011 at 18:50
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);
}
1
  • 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 stackoverflow.com/questions/5767325/…
    – Aaron_H
    Nov 5, 2015 at 4:08
0

it worked for me..

countries.results= $.grep(countries.results, function (e) { 
      if(e.id!= currentID) {
       return true; 
      }
     });
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>

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

The accepted answer is problematic as it attaches a function to the Array prototype. That function will show up whenever you run thru the array using a for loop:

for (var key in yourArray) {
    console.log(yourArray[key]);
}

One of the values that will show up will be the function. The only acceptable way to extend base prototypes (although it is generally discouraged as it pollutes the global space) is to use the .defineProperty method:

Object.defineProperty(Object.prototype, "removeValue", {
    value: function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] === val) {
                this.splice(i, 1);
                i--;
            }
        }
        return this;
    },
    writable: true,
    configurable: true,
    enumerable: false
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.