-6

How i can find index of object in an array from JSON in a component?

My JSON file looks like this,

{
 "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",
    }
    ...
}

Here is my project detail component

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

Now i want to somehow get current index of object.

Sohail Mushtaq Awan
  • 666
  • 1
  • 8
  • 11

1 Answers1

2

The Array.prototype.findIndex() method returns an index of the first element in the array that satisfies the provided testing function.

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

[12, 5, 8, 130, 44].findIndex(isBigEnough); // 3
Jérémie L
  • 770
  • 4
  • 14