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');
Sign up to request clarification or add additional context in comments.

4 Comments

Note: jQuery is necessary to use this function
Does this not break the index, because the index changes during execution if an element is removed.
@JohnStrickler: can you rewrite this without jquery please. I don't like librairies.
According to the documentation api.jquery.com/each, $.each doesn't take two arguments (anymore?).
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 Comments

+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!
@JimG.: Glad I could be of help :-)
@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]
@GX.: Can you please change the accepted answer to this answer?
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.
22

Try this:

var COUNTRY_ID = 'AL';

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

3 Comments

+1: Worth noting that it isn't supported in IE < 9
@Jeremy Heiler: for IE such function can be added from code provided here: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
You referenced the same link I referenced :-P
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"]);

Comments

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

Comments

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 Comment

I think he wants to delete the entire object from the array. Instead of deleting the property from the object.
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 Comment

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/…
0

it worked for me..

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

Comments

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>

Comments

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

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.