Jamil89
Jamil89

Reputation: 165

JSON & angularjs. Filter an array by ID (and not by index)

How can i filter this JSON by an element (in this case the id) without using the index?

     ABC: [{
 ID: home,
 elementsHome: [
       {
       el1: x,
       el2: y},
       {
       el3: d,
       el4: s}]
  },
  {
  ID: payments,
  elementsPaymets: etc...
  }];

An html with an ng-repeat like this doesn't work: ng-repeat: item in ABC.element2 | filter: {id:"good"}. The only way is re-write ABC this way ABC[0] but this is what I want to avoid.

Thanks

Upvotes: 1

Views: 400

Answers (2)

shadymoses
shadymoses

Reputation: 3463

ABC.filter(function(item) {
  return item.id === 'whatever you want to check'
})

Array.prototype.filter iterates over an array and returns a new filtered array based on a function you provide. That function receives the array item, index and the array as parameters. Your function must return true or false. If an iteration returns true it's kept and if it returns false it's removed.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter


Edit

It sounds like you're actually trying to find a single item in an array and access a property on it. So if you know your id:

var curId = 'HOME'

Then you can just find the item that has that id:

var item = ABC.find(function(item) {
  return item.id === curId
})

If there's a match you can access the key you want:

item && item['elements' + curId.substr(0, 1) + curId.substr(1).toLowerCase()]

Upvotes: 3

Pramod Patil
Pramod Patil

Reputation: 2763

_.filter(ABC, { 'id': 'good' });

Upvotes: 0

Related Questions