I have a Component and a Service:
Component:
You need to use method Array.filter:
this.persons = this.personService.getPersons().filter(x => x.id == this.personId)[0];
or Array.find
this.persons = this.personService.getPersons().find(x => x.id == this.personId);
Assume I have below array:
Skins[
{Id: 1, Name: "oily skin"},
{Id: 2, Name: "dry skin"}
];
If we want to get item with Id = 1
and Name = "oily skin"
, We'll try as below:
var skinName = skins.find(x=>x.Id == "1").Name;
The result will return the skinName is "Oily skin".
Use this code in your service:
return this.getReports(accessToken)
.then(reports => reports.filter(report => report.id === id)[0]);
Transform the data structure to a map if you frequently use this search
mapPersons: Map<number, Person>;
// prepare the map - call once or when person array change
populateMap() : void {
this.mapPersons = new Map();
for (let o of this.personService.getPersons()) this.mapPersons.set(o.id, o);
}
getPerson(id: number) : Person {
return this.mapPersons.get(id);
}
Try this
let val = this.SurveysList.filter(xi => {
if (xi.id == parseInt(this.apiId ? '0' : this.apiId))
return xi.Description;
})
console.log('Description : ', val );
You could combine .find
with arrow functions and destructuring. Take this example from MDN.
const inventory = [
{name: 'apples', quantity: 2},
{name: 'bananas', quantity: 0},
{name: 'cherries', quantity: 5}
];
const result = inventory.find( ({ name }) => name === 'cherries' );
console.log(result) // { name: 'cherries', quantity: 5 }