0

I have an interface class and JSON file which I would like to convert to a list and work on it. for instance , getting Racename from every object in the JSON into a list\array. is it possible? that's the interface:

interface IRunners{
Racename: string;
Category:number; 
Gender:string; 
Work:string; 
FullName:string; 
Rank:number;
Point:number;
Numparticipant:number;
rankparticipant:number;
precentagePart:string; 
NumRaces:number; 
RaceTime:string; 
rankCat:number; 
PointCat:number; 
RaceDate:string;
}

This is the JSON file (Runners.json):

[
  {"Racename":"A1","Category":34,"Gender":"זכר","Work":"AMDOCS","FullName":"Simon Work ","Rank":1,"Ponit":1,"Numparticipant":0,"rankparticipant":0,"precentagePart":"0","NumRaces":1,"RaceTime":"2018-10-18T00:34:20","rankCat":1,"PointCat":1,"RaceDate":"2018-10-05"}
] 

I'm subscribing it as follow:

  this.runnerService.getRunners().subscribe(
        runners=>{
          this.runners = runners;
          this.filteredCompetitions = this.runners;
          this.filteredRunners = this.runners;
        }

I would like to convert the runners JSON into an array in order to make some changes and get some data out of it. I'm a newbie to Typescript and Angular so probably I'm making some mistakes.

Liam
  • 27,717
  • 28
  • 128
  • 190
JumpIntoTheWater
  • 1,306
  • 2
  • 19
  • 46

1 Answers1

2

You can use Array#map().

// Assumes runners.json is a file in the same directory as this file
const jsonArray = require("./runners.json")

// // returns ["A1"]
const listOfRacenames = jsonArray.map(d => d.Racename)
Mikis
  • 80
  • 2
  • 7
  • means I need to change my interface to your suggestion? – JumpIntoTheWater Dec 07 '18 at 10:24
  • Are you trying to generate TypeScript interfaces from the JSON file? It's not clear where you're starting and where you'd like to end up. – Mikis Dec 07 '18 at 10:29
  • as a newbie, I'm nut sure what I'm trying to do, but I would like to end up iterating the JSON and get some data from every object in it – JumpIntoTheWater Dec 07 '18 at 10:31
  • In that case, my answer above will do what you need it to do. There's also [Array#forEach()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) if you'd like to perform some arbitrary operation on each of your JSON objects — i.e., you don't want to return a result. Let me know if that makes sense. – Mikis Dec 07 '18 at 10:35
  • it makes sense, the only problem currently is my JSON is in different file(`runners.json`) and I'm not sure I can implement it exactly as you suggested. am I wrong? 10x btw... – JumpIntoTheWater Dec 07 '18 at 10:37
  • Try ```require('path/to/your/json/file.json')```. – Mikis Dec 07 '18 at 10:42
  • Updated answer above to use an external JSON file. – Mikis Dec 07 '18 at 10:47