KeyValue Pipe In Angular

KeyValue Pipe In Angular

In this article, we will learn about the how to make use of KeyValue pipe with example. The KeyValue Pipe creates an array of key-value pairs from an Object or Map. This may be used in conjunction with ngFor to loop through the object keys. The compareFn argument of the keyValue can be used to set the custom sort for the pipe.

How it works?

Consider the following object, as well as a map object. It possesses the properties a,b and c. We can't iterate over it with ngFor because it requires an array. The KeyValue stream comes into play at this point. It'll turn them into a key-value pair array.

obj = {
  c: 123,
  b: 456,
  a: 789,
};

mapObj = new Map([
   ['c', 123],
   ['b', 446],
   ['a', 789],
]);

In Angular, we use keyValue exactly like any other pipe, as demonstrated below.
obj | keyvalue
 
mapObj | keyvalue

The keyValue function transforms them and returns them in the format shown below. Each property of the object a: 789 is changed to an object with the name an as the key and the value 789 as the value (key:a, value:789). It returns an array of such objects that it has created.
obj = [
   { key:a, value:789 },
   { key:b, value:446 },
   { key:c, value:123 },
 ];

We can now loop through it and display the content using the ngFor.
<ul>
  <li *ngFor="let item of obj | keyvalue">
    {{item.key}} ---> {{item.value}}</li>
</ul>
 
//output
 
a ---> 789
b ---> 456
c ---> 123

Default Sorting

The key is used to order the results array in the KeyValue pipe. The given example demonstrates this. Despite the fact that our object was c,b and a, it was sorted as a,b,c. The defaultComparator is used by the keyValue pipe to sort the result. It makes use of
  1.  If the keys are numbered, place them in ascending order.
  2. If the keys are strings, sort them alphabetically.
  3. If the keys are of various types. Then convert them to string values and use Alphabetical Order to sort them.
  4. Put the key at the end of the sort if it is either Null or undefined.

Custom Sorting

You can personalize it by giving the keyValue pipe a custom sort function (compareFn) as the first parameter.

The syntax for compareFn is as follows. It must return a number and accepts the first and second keyValue. If the values are equal, the number must be zero; otherwise, it must be either a negative or positive integer.
compareFn (a: KeyValue, b: KeyValue) => number 

Three compareFns are listed below.
orderOriginal = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {
  return 0
}
  
orderbyValueAsc = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {
   return a.value > b.value ? -1 : (a.value > b.value) ? 0 : 1  
}
 
orderbyValueDsc = (a: KeyValue<number,string>, b: KeyValue<number,string>): number => {
  return a.value > b.value ? 1 : (a.value > b.value) ? 0 : -1  
}

<ul>
  <li *ngFor="let item of obj | keyvalue">
    {{item.key}} ---> {{item.value}}</li>
</ul>
 
//Output
a ---> 789
b ---> 456
c ---> 123
 
 
<ul>
  <li *ngFor="let item of obj | keyvalue : orderOriginal">
    {{item.key}} ---> {{item.value}}</li>
</ul>
 
//Output
b ---> 456
c ---> 123
a ---> 78
 
 
<ul>
  <li *ngFor="let item of obj | keyvalue : orderbyValueAsc ">
    {{item.key}} ---> {{item.value}}</li>
</ul>
 
//Output
a ---> 789
b ---> 456
c ---> 123
 
 
<ul>
  <li *ngFor="let item of obj | keyvalue : orderbyValueDsc ">
    {{item.key}} ---> {{item.value}}</li>
</ul>
 
//Output
c ---> 123
b ---> 456
a ---> 789

KeyValue Pipe Example

Consider the following dog breeds. The list is sorted in this example based on the number of sub breeds. The finished code is as follows.
breeds=
   {
     "corgi": ["cardigan"],
     "deerhound": ["scottish"],
     "bulldog": ["boston", "english", "french"],
     "mastiff": ["bull", "english", "tibetan"],
     "australian": ["shepherd"],
     "greyhound": ["italian"],
     "buhund": ["norwegian"],
     "hound": ["afghan", "basset", "blood", "english", "ibizan", "plott", "walker"],
     "bullterrier": ["staffordshire"],
   }

CompareFn

orderClause = (a: KeyValue<number,[string]>, b: KeyValue<number,[string]>): number => {
  return a.value.length > b.value.length ? -1 : (a.value.length > b.value.length) ? 0 : 1  
}

Template

<ul>
  <li *ngFor="let item of breeds | keyvalue : orderClause ">
    {{item.key}} ---> {{item.value}}</li>
</ul>

The output

hound ---> afghan,basset,blood,english,ibizan,plott,walker
bulldog ---> boston,english,french
mastiff ---> bull,english,tibetan
corgi ---> cardigan
deerhound ---> scottish
australian ---> shepherd
greyhound ---> italian
buhund ---> norwegian
bullterrier ---> staffordshire

Conclusion

In this article, we learned about the how to make use of KeyValue pipe with example. The KeyValue Pipe creates an array of key-value pairs from an Object or Map.

I hope this article helps you and you will like it.👍

If you have any doubt or confusion then free to ask in comment section.

Post a Comment

Previous Post Next Post