Angular 2 TypeScript如何在数组中查找元素


131

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

零件:

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('personID')的Person Item。我从Routeparam获得的personID。为此,我需要foreach循环?但是我还没有找到解决方案。


11
您可以像这样的id来找到一个元素
person.find

Answers:


255

您需要使用方法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);

2
@SaravananNandhan,方法this.personService.getPersons()返回undefined
Andrei Zhytkevich

4
@AndreiZhytkevich我们不应该使用三重等于吗?
antonioplacerda

@antonioplacerda,是的,可以。但是,对于这个问题,它并不是太重要。
Andrei Zhytkevich

1
最初,该代码对我来说似乎很神秘,但将“ find(x => x.id == this.personId”读为“ find x,其中x的ID等于此人的ID”可能会有所帮助)人,但对我而言,这更容易记住
Rizki Hadiaturrasyid

69

假设我有下面的数组:

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

如果我们想用Id = 1和获得物品Name = "oily skin",我们将尝试如下操作:

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

结果将返回skinName为“油性皮肤”。

请尝试一下,谢谢,并致以最诚挚的问候!

在此处输入图片说明


4
感谢您提供此代码段,它可能会提供一些有限的短期帮助。通过说明为什么这是解决问题的好方法,适当的解释将大大提高其长期价值,对于其他存在类似问题的读者来说,这样做将更为有用。请编辑您的答案以添加一些解释,包括您所做的假设。
Toby Speight,

1
您将如何对最初为空然后动态填充的数组执行此操作...编译时似乎存在问题....属性(例如Id)变得未知。
rey_coder

您好@rey_coder,我认为我们应该在实现获取数组元素项之前检查数组是否不为null。像:testArray = []; testArrayItem = testArray.length> 0?testArray.find(x => x.Id == 1)。名称:'testArray null'; console.log(testArrayItem);
Hai Dinh

1
嗨@ hai-dinh,排序问题。谢谢。
rey_coder

9

如果您经常使用此搜索,则将数据结构转换为地图

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

8

尚未提及的一个不错的选择是将其.find与箭头功能结合使用并进行销毁。以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 }


4

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

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

1

试试这个

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

      console.log('Description : ', val );
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.