[javascript] remove item from array using its name / value

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

This question is related to javascript jquery arrays

The answer is


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

Try this:

var COUNTRY_ID = 'AL';

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

You can do it with _.pullAllBy.

_x000D_
_x000D_
var countries = {};_x000D_
_x000D_
countries.results = [_x000D_
    {id:'AF',name:'Afghanistan'},_x000D_
    {id:'AL',name:'Albania'},_x000D_
    {id:'DZ',name:'Algeria'}_x000D_
];_x000D_
_x000D_
// Remove element by id_x000D_
_.pullAllBy(countries.results , [{ 'id': 'AL' }], 'id');_x000D_
_x000D_
// Remove element by name_x000D_
// _.pullAllBy(countries.results , [{ 'name': 'Albania' }], 'name');_x000D_
console.log(countries);
_x000D_
.as-console-wrapper {_x000D_
  max-height: 100% !important;_x000D_
  top: 0;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_


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

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"]);

it worked for me..

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

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

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

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?