remove item from array using its name / value
Asked Answered
R

11

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

Robtrobust answered 10/6, 2011 at 18:34 Comment(0)
C
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');
Cyprinid answered 10/6, 2011 at 18:52 Comment(5)
+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!Platte
@JimG.: Glad I could be of help :-)Cyprinid
@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]Aliunde
@GX.: Can you please change the accepted answer to this answer?Platte
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.Nomenclator
G
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');
Gallium answered 10/6, 2011 at 18:48 Comment(4)
Note: jQuery is necessary to use this functionNumerous
Does this not break the index, because the index changes during execution if an element is removed.Popular
@JohnStrickler: can you rewrite this without jquery please. I don't like librairies.Militarize
According to the documentation api.jquery.com/each, $.each doesn't take two arguments (anymore?).Hufuf
C
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');
Cyprinid answered 10/6, 2011 at 18:52 Comment(5)
+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!Platte
@JimG.: Glad I could be of help :-)Cyprinid
@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]Aliunde
@GX.: Can you please change the accepted answer to this answer?Platte
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.Nomenclator
F
22

Try this:

var COUNTRY_ID = 'AL';

countries.results = 
  countries.results.filter(function(el){ return el.id != COUNTRY_ID; });
Faris answered 10/6, 2011 at 18:51 Comment(3)
+1: Worth noting that it isn't supported in IE < 9Iglesias
@Iglesias Heiler: for IE such function can be added from code provided here: developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…Faris
You referenced the same link I referenced :-PIglesias
S
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"]);
Stronghold answered 30/12, 2015 at 2:34 Comment(0)
B
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;
}
Bergmann answered 24/3, 2014 at 11:9 Comment(0)
N
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];
      }
   }
}
Numerous answered 10/6, 2011 at 18:42 Comment(1)
I think he wants to delete the entire object from the array. Instead of deleting the property from the object.Gallium
N
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);
}
Noncommittal answered 13/6, 2014 at 3:22 Comment(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 #5767825Modiste
M
0

it worked for me..

countries.results= $.grep(countries.results, function (e) { 
      if(e.id!= currentID) {
       return true; 
      }
     });
Md answered 18/1, 2017 at 6:33 Comment(0)
S
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>
Sitra answered 4/10, 2018 at 6:5 Comment(0)
R
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);
    }
}
Rolland answered 27/10, 2019 at 11:40 Comment(0)
B
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
});
Bioplasm answered 24/2, 2022 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.