Ambrown
Ambrown

Reputation: 361

Angular: How do you identify JSON objects with id's?

To hopefully simplify my question, I have broken it down like so:

What I do understand

If this is my object:

{ 
     things: [{
         'text': 'version'
         'short': 'v',
         'order': 1,
         'id': 'A'
     },{
         'text': 'update'
         'short': 'u',
         'order': 2,
         'id': 'B'
     }]
}

...then this is my type class:

 export class Thing {
     text: string;
     short: string;
     order: number;
     id: string;
 }

What I do not understand

If this is my data:

 { things: {
         'A': {
             'text': 'version'
             'short': 'v',
             'order': 1,
             'id': 'A'
         },
         'B': {
             'text': 'update'
             'short': 'u'
             'order': 2
             'id': 'B'
         }
     }
 }

...then the type class is...?

I have tried some really creative, ineffective tries to get this to work to no avail. I'm also hoping I can make sense of what to do with this non-array array (no square-brackets). Apologies if this is a duplicate.

Upvotes: 2

Views: 218

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074555

In that second situation, your things type would be an index type like this:

interface ThingHolder {
    [key: string]: Thing;
}

That says that the keys are strings and the values are Things.

The interface for data would be something that has a things property of that type:

interface AppropriateNameHere {
  things: ThingHolder;
}

So then, the compiler is happy with this:

const data : AppropriateNameHere = {
  things: {
    'A': {
      'text': 'version',
      'short': 'v',
      'order': 1,
      'id': 'A'
    },
    'B': {
      'text': 'update',
      'short': 'u',
      'order': 2,
      'id': 'B'
    }
  }
};

Live Example on the TypeScript playground.

Upvotes: 4

Related Questions