1

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
}
Kiss Koppány
  • 919
  • 5
  • 15
  • 33

2 Answers2

2

With linq.js, you need do convert the data ToDictionary, get the wanted item with Single from enumerable and remove the item.

Then you have to rebuild the array again from dictionary via enumerable and select to array.

Et voilà!

var data = [{ id: 1, name: 'John', age: 20}, { id: 2, name: 'Josh', age: 34}, { id: 3, name: 'Peter', age: 32}, { id: 4, name: 'Anthony', age: 27}],
    enumerable = Enumerable.From(data),
    dictionary = enumerable.ToDictionary();

dictionary.Remove(enumerable.Single(s => s.id === 3));
console.log(dictionary.ToEnumerable().Select(s => s.Key).ToArray());
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1
   //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

Sunil B N
  • 4,159
  • 1
  • 31
  • 52
  • thank you for your solution, very useful :) however, I'd like to solve the issue with linq.js if its possible, but if no one responds soon I'll accept your answer as it solved my problem even if in another way. – Kiss Koppány Sep 08 '16 at 08:55
  • it doesn't matter, in their methods, they will be doing something similar to what I have coded above.. For complex functionalities/or browser dependent code we should stick to libraries.. I don't see the issue for this though. – Sunil B N Sep 08 '16 at 09:03
  • well, you might be right, for this little piece of code using a library is unnecessary – Kiss Koppány Sep 08 '16 at 09:32