如何在数组中查找元素

我有一个组件和一个服务:

组成部分:

export class WebUserProfileViewComponent {
persons: Person [];
personId: number;
constructor( params: RouteParams, private personService: PersonService) {
          

        

this.personId = params.get('id');
this.persons =  this. personService.getPersons();
console.log(this.personId);
}
}

服务范围:

@Injectable()
export class PersonService {
getPersons(){
var persons: Person[] = [
{id: 1, firstName:'Hans', lastName:'Mustermann', email: 'mustermann@test.com', company:'Test', country:'DE'},
{id: 2, firstName:'Muster', lastName:'Mustermann', email: 'mustermann@test.com', company:'test', country:'DE'},
{id:3, firstName:'Thomas', lastName:'Mustermann', email: 'mustermannt@tesrt.com', company:'test', country:'DE'}
];
          

return persons;
}
}

我希望获取 ID 为“ Person”的项(“ PersonID”)。我从 Routeparams得到的人员编号。我需要 foreach 循环吗?但我还没找到解决办法。

541795 次浏览

你需要使用方法 Array.filter:

this.persons =  this.personService.getPersons().filter(x => x.id == this.personId)[0];

Array.find

this.persons =  this.personService.getPersons().find(x => x.id == this.personId);

在您的服务中使用以下代码:

return this.getReports(accessToken)
.then(reports => reports.filter(report => report.id === id)[0]);

如果经常使用此搜索,请将数据结构转换为映射

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);
}

从 TypeScript 中你可以使用原生 JS 数组 filter ()方法:

let filteredElements=array.filter(element => element.field == filterValue);

它返回一个只包含与原始数组(0、1或更多)匹配的元素的数组

参考文献: Https://developer.mozilla.org/it/docs/web/javascript/reference/global_objects/array/filter

假设我有以下数组:

Skins[
{Id: 1, Name: "oily skin"},
{Id: 2, Name: "dry skin"}
];

如果我们想得到的项目与 Id = 1Name = "oily skin",我们将尝试如下:

var skinName = skins.find(x=>x.Id == "1").Name;

结果将返回的皮肤名称是“油性皮肤”。

enter image description here

试试这个

          let val = this.SurveysList.filter(xi => {
if (xi.id == parseInt(this.apiId ? '0' : this.apiId))
return xi.Description;
})


console.log('Description : ', val );

可以将 .find与箭头函数和解构结构相结合。

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 }