ArticleZip > Typescript Convert Object To Array Because Ngfor Does Not Supports Iteration Of Object

Typescript Convert Object To Array Because Ngfor Does Not Supports Iteration Of Object

When working with Angular applications, you might have come across a common issue where you need to iterate over an object in your component template using `*ngFor`. However, `*ngFor` does not directly support iteration over objects, so you need to convert your object into an array to leverage this feature. In this guide, we will walk you through the process of converting an object into an array using TypeScript.

To begin with, let's consider a scenario where you have an object that you'd like to iterate over in your Angular template:

Typescript

// Sample object
let sampleObject = {
  key1: 'value1',
  key2: 'value2',
  key3: 'value3'
};

If you attempt to use this object directly in an `*ngFor` directive in your component template, you will encounter an error because `*ngFor` only works with arrays. To overcome this limitation, you can convert your object into an array of key-value pairs. Here's how you can achieve this using TypeScript:

Typescript

// Convert object to array
let objectArray = Object.keys(sampleObject).map(key => ({ key, value: sampleObject[key] }));

In the above code snippet, we first obtain an array of keys from the object using `Object.keys()`. We then utilize the `map()` function to transform each key into an object containing both the key and its corresponding value from the original object, thus creating an array of key-value pairs.

Now that we have our object converted to an array, you can seamlessly iterate over it in your Angular template using `*ngFor`. Here's an example of how you can loop through the array in your component template:

Html

<ul>
  <li>
    Key: {{ item.key }} - Value: {{ item.value }}
  </li>
</ul>

By implementing the above code snippet in your Angular component template, you will now be able to iterate over each key-value pair in the `objectArray` array effortlessly.

Remember that this conversion step is essential when dealing with objects and iterating over their properties in your Angular application. By transforming objects into arrays of key-value pairs, you can harness the full power of Angular's `*ngFor` directive without encountering any roadblocks.

In conclusion, we have explored how to convert an object into an array in TypeScript to facilitate iteration in Angular applications. By following the simple steps outlined in this guide, you can effectively resolve the issue of `*ngFor` not supporting direct iteration over objects. Happy coding!