如何从JSON中找到数组中对象的索引 - Angular 2

时间:2017-02-08 13:53:24

标签: javascript angular indexof

  

如何从组件中的JSON中找到数组中的对象索引?

我的JSON文件看起来像这样,

{
 "Projects":[
  {
    "id":"proj-1",
    "name":"Design for creative",
    "meta":{
        "date":"03 November, 2016",
        "url":"http://www.pixelsocket.com",
    },
    {
    "id":"proj-2",
    "name":"Design for creative",
    "meta":{
        "date":"03 November, 2016",
        "url":"http://www.pixelsocket.com",
    }
    ...
}

这是我的项目详细信息组件

export class ProjectDetailComponent implements OnInit{

project: Project;

projectId: string;

totalProjects: Project[] = [];

currentProjectIndex:number;


constructor(private dataService: DataService, private route:   ActivatedRoute) {
  this.projectId = route.snapshot.params['id'];
}

ngOnInit() {
  //Getting Projects Data
  this.dataService.getProjects().then(
    (data: any) =>  this.totalProjects = data
  );

  this.route.params
  .switchMap((params: Params) =>    this.dataService.getProject(this.projectId))
  .subscribe(data => this.project = data);
 }
}

现在我想以某种方式获取对象的当前索引。

1 个答案:

答案 0 :(得分:2)

Array.prototype.findIndex()方法返回数组中第一个满足提供的测试函数的元素的索引。

function isBigEnough(element) {
  return element >= 15;
}

[12, 5, 8, 130, 44].findIndex(isBigEnough); // 3