DEV Community

loading...

Angular KeyValue Pipe 🚀

maggy24 profile image Magdalena Chmura ・1 min read

KeyValue pipe is an Angular built-in feature that transforms objects or maps into an array of key-value pairs.

If you've been working with Angular since its early versions, you might have missed it as the KeyValue pipe was introduced in Angular 6.1.

Let's see it in action 🔥

Imagine a simple object that stores student's names as a key and an array of grades as a value.

  const students = {
    Susane: [4, 3, 2, 1, 5],
    Jenifer: [3, 5, 2, 2],
    John: [5, 3, 3, 4, 1]
  };
Enter fullscreen mode Exit fullscreen mode

With KeyValuePipe you can iterate over objects directly from the template.

<ul *ngFor="let student of (students | keyvalue)">
  <li>{{ student.key }}'s grades: {{ student.value }}</li> 
</ul>
Enter fullscreen mode Exit fullscreen mode

It is a clean and declarative solution that will allow you to clean up your templates.

Hope you're having a great one, and I'll see you for more 60 Seconds of Angular posts in the future 🥳

Discussion (2)

pic
Editor guide
Collapse
joellau profile image
Joel Lau

great read!

Collapse
lawcia profile image
Lawrencia

Useful thanks!