0

Please assist, am trying to transform an object to an instance of something. I have the following data as object from an API:

{
"0": {
    "0": {
        "1": 2
    },
    "1": {
        "1": 5
    },
    "2": {
        "1": 9
    },
    "3": {
        "1": 3
    },
    "4": {
        "1": 1
    }
},
"1": {
    "0": {
        "1": 7
    },
    "1": {
        "1": 6
    },
    "2": {
        "1": 10
    },
    "3": {
        "1": 8
    },
    "4": {
        "1": 4
    }
  }
}

my enums are as follows :

  export enum Enum3 {
    week1 = 0,
    ....
    week4
  }


   export enum Enum2 {
        day1 = 0,
        .....
        day10
   }

   export enum Enum1 {
        monday = 0,
        .....
        friday
   }

tried the following to declare but didn't work:

         // number is the number of racers entering the race
        let RaceDay: {[key: Enum1 ]: number };
        let Days: {[key: Enum2 ]: RaceDay[Key] };
        let Weeks: {[key: Enum3 ]:  Days[Key] };

        Weeks = ApiData; // data above.

How do i declare or instantiate such an object ? thank you.

3
  • A bit more code would be helpful. For example the Enum declaration Commented May 23, 2018 at 8:15
  • What is the code that gets the JSON from the API? You are probably not deserializing your JSON. Probably there is missing a call to JSON.parse(). Commented May 23, 2018 at 8:20
  • hi, i've edited the question see above. Commented May 23, 2018 at 8:57

1 Answer 1

1

You have a 3 times nested object structure:

interface RaceDay {
  [key: string]: number
}
interface Days {
  [key: string]: RaceDay
}
interface Weeeks {
  [key: string]: Days
}

const data: Weeks = { } as Weeks; // your object with type of 'Object' as above

assigning your object works for me. Hope that's helping.

Sign up to request clarification or add additional context in comments.

3 Comments

i am getting the following error Type 'Object' is not assignable to type 'Weeks'. The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
Are you using angular httpclient or similar? Maybe try const data: Weeks = {} as Weeks. If you use something like httpClient from angular you can do this.http.get<Weeks>(url);.
if your data is type 'Object' the as Weeks at the end should work. Tested it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.