0

I have from the server the following structure (as appropriate JSON structure)

Orga1
| + Department1
| |  + Role1
| |  + Role2
| + Department2
| |  + Role10
| |  + Role11
Orga 2
| + DepartmentAB
| |  + RoleAB1
...

I was thinking to have in an object in Angular like

export interface Organization {
  name: string;
  lstDeparments: Department [];
}
export interface Department {
  name: string;
  lstRoles: string [];
}

But somehow I have no real clue how to set up the matching interface in Angular. Because the attribute name is dynamically changing (e.g. Orga1, Orga2) and the list of attributes needs to be filled as well dynamically with the content.

Any ideas how to setup the interface properly? (to have automatic conversion)

1 Answer 1

2

You have a specific syntax for this kind of data structure :

interface Payload {
  [key: string]: Orga;
}

interface Orga {
  [key: string]: Department;
}

interface Department {
  [key: string]: Role;
}

If you want the list of Orgas, you have to iterate on an object, not on an array.

You can do this with Object.keys or in more recent browsers (or if you have a polyfill), Object.entries :

const orgas = Object.keys(payload).map(key => payload[key]);
const orgas = Object.entries(payload).map(([key, value]) => value);

You can also use generation function through Symbol.iterator to iterate over your objects, but I think it's a bit overkill :

const payload = {
  orga1: { name: 'orga 1' },
  orga2: { name: 'orga 2' },
  [Symbol.iterator]: function *() {
    for (const key of Object.keys(this)) {
      yield this[key];
    }
  }
};

for (const value of payload) {
  console.log(value);
}

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

8 Comments

(you can of course add other properties such as "name", it's just that those that aren't recognized will be considered as a sub-interface)
@ashish.gd from the given tructure, it doesn't seem like it. The payload contains a list of Orgas, which are all named. So it's not an array, it's an object containing dynamic properties, that are each a sub-interface.
Yes, my bad. I read it incorrectly. Deleting my comment to avoid any confusion to OP or anyone else.
Reponse come quicker than I could implement and think about. Couldn't accept the answer earlier :-) Thx this works great +1
Although the implementation works I have tiny problems with the solution :-/. Namely how to get a list of e.g. Organisation. Trying Payload.map(item=>Object.keys(item)[0]); is a valid (?) idea in debug - but in Angular I get a compile error cuz map is not provided in Orga.
|

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.