Hello Friends 👋,

Welcome To Infinitbility! ❤️

Every time, we got an array in an object and we have to use arrays from objects.

Today, we will see how we will use an array from an object in TypeScript.

In this tutorial, we will take the example of an object in an array of objects and we will iterate every row of arrays.

Let’s start Today’s tutorial How to get an array from JSON object in typescript?

let’s assume we have the following response from API.

{
  status: 200,
  users: [
    { id: 1, name: 'infinitbility' },
    { id: 2, name: 'notebility' },
    { id: 3, name: 'repairbility' }
  ]
}

To create the above API response in typescript we have followed below code example of the API response interface.

interface User {
  id: number;
  name: string;
}

interface Api {
  status: number;
  users: Array<User>;
}

let users: Array<User> = [
  { id: 1, name: 'infinitbility' },
  { id: 2, name: 'notebility' },
  { id: 3, name: 'repairbility' },
];

let apiResponse: Api  = {
  status: 200,
  users: users
}

Now, we have the response of objects with contain array of objects let’s see how we can iterate the array.

If you also the following code to iterate API response first check API response and if OK status, use for loop to get rows.

interface User {
  id: number;
  name: string;
}

interface Api {
  status: number;
  users: Array<User>;
}

let users: Array<User> = [
  { id: 1, name: 'infinitbility' },
  { id: 2, name: 'notebility' },
  { id: 3, name: 'repairbility' },
];

let apiResponse: Api  = {
  status: 200,
  users: users
}

if(apiResponse.status == 200){
  for(let user of apiResponse.users){
    console.log('user', user);
  }
}

Output

typescript, object, arrays, example
TypeScript, iterate object array example.

Thanks for reading…