Houssem Balty
Houssem Balty

Reputation: 33

Filter json collection by id in Javascript

So I'm trying to retrieve a collection from this list below by the id in Javascript. How can I do that? I've been searching lately to find a way but I couldn't.

   {'id':1,"firstTeam":"Barcelona","secondTeam":"Real       Madrid","Time":"14:00","commentator":"Unknown","championship":"UEFA","channel":"BEIN SPORT","iframe":'<iframe width="560" height="315" src="https://www.youtube.com/embed/pQRO_5dtqrk" frameborder="0" allowfullscreen></iframe>'}

   {'id':2,"firstTeam":"Barcelona","secondTeam":"Real Madrid","Time":"14:00","commentator":"Unknown","championship":"UEFA","channel":"BEIN SPORT","iframe":'<iframe width="560" height="315" src="https://www.youtube.com/embed/pQRO_5dtqrk" frameborder="0" allowfullscreen></iframe>'}

Upvotes: 0

Views: 1266

Answers (2)

Batuta
Batuta

Reputation: 1714

Use Array.prototype.filter():

 var testArray = [{'id':1,"firstTeam":"Barcelona","secondTeam":"Real Madrid","Time":"14:00","commentator":"Unknown","championship":"UEFA","channel":"BEIN SPORT","iframe":'<iframe width="560" height="315" src="https://www.youtube.com/embed/pQRO_5dtqrk" frameborder="0" allowfullscreen></iframe>'},
{'id':2,"firstTeam":"Barcelona","secondTeam":"Real Madrid","Time":"14:00","commentator":"Unknown","championship":"UEFA","channel":"BEIN SPORT","iframe":''}];

var filtered = testArray.filter(filterFunction);

// Let's assume you want to filter by ID, stored in $scope variable.
$scope.filterById = 2;


function filterFunction(val) {
  return value.id == $scope.filterById;
}

Upvotes: 1

Artem
Artem

Reputation: 833

It is dup of Find object by id in an array of JavaScript objects

Using jQuery.grep:

$.grep(myArray, function(e){ return e.id == id; })[0]

Upvotes: 0

Related Questions