Kiss Koppány Kiss Koppány - 2 months ago 52
Javascript Question

Removing element from object array with linq.js

I have started using linq.js a while ago, and found it very useful, but there's an issue I really can't solve somehow. I'm using angular, and I have a simple json array with the following structure:

[
{ id: 1, name: 'John', age: 20},
{ id: 2, name: 'Josh', age: 34},
{ id: 3, name: 'Peter', age: 32},
{ id: 4, name: 'Anthony', age: 27},
]


I'm looking for the best (or at least a working) example wich could help me understanding how to remove an element of this array by the
id
property. I have found some examples with simple array (but not with json elements), those haven't helped me too much.

I have the following function to do the remove part:

this.removePerson = function(id) {
//here's how I access the array
vm.people
}

Answer
   //assuming your sample data
    var vm = {};
    vm.people = [
      { id: 1, name: 'John', age: 20},
      { id: 2, name: 'Josh', age: 34},
      { id: 3, name: 'Peter', age: 32},
      { id: 4, name: 'Anthony', age: 27},
    ];

    //just loop through and delete the matching object
    this.removePerson = function(id) {
      for(var i=0;i<vm.people.length;i++){
          if(vm.people[i].id == id){
          vm.people.splice(i, 1);//removes one item from the given index i
          break;
          }
      }
    };

JSBin here

Comments