0

I got a list of Peoples (people object) from my json API and I saved it in a variable accessed via this.people.

I need to access the person where his pivot object age = 15 assuming there is only one pivot object defind with age of 15.

  1. Can I access this specific object with angular 2?
  2. If not, will I have to change my API to make a new request for it?

Thanks in advance!

1 Answer 1

2

You could implement a custom pipe:

@Pipe({
  name: 'filter'
})
export class FilterPipe {
  transform(val) {
    return val.filter((elt) => elt.age === 15);
  }
}

and use it this way:

{{people | filter}}

Don't forget to add your pipe into the pipes attribute of the component where you want to use it:

@Component({
  (...)
  pipes: [ FilterPipe ]
})

You could make this pipe a bit generic with parameters:

@Pipe({
  name: 'filter'
})
export class FilterPipe {
  transform(val, params) {
    var field = params[0];
    var fieldValue = params[1];
    return val.filter((elt) => elt[field] === fieldValue);
  }
}

and use it this way:

{{people | filter:age:15}}
Sign up to request clarification or add additional context in comments.

2 Comments

What's the "elt" variable?
elt is an element of array. It's provided to the arrow function... The filter method iterates over the values of the array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.