I am facing challenges with organizing an array of objects in Angular2.
The structure of the object is as follows:
[
{
"name": "t10",
"ts": 1476778297100,
"value": "32.339264",
"xid": "DP_049908"
},
{
"name": "t17",
"ts": 1476778341100,
"value": "true",
"xid": "DP_693259"
},
{
"name": "t16",
"ts": 1476778341100,
"value": "true",
"xid": "DP_891890"
}
]
The objects are stored in the values
variable.
I simply want to use the *ngFor
loop to sort them based on the name
property.
<table *ngIf="values.length">
<tr *ngFor="let elem of values">
<td>{{ elem.name }}</td>
<td>{{ elem.ts }}</td>
<td>{{ elem.value }}</td>
</tr>
</table>
I attempted to achieve this using pipes, but without success. Any assistance would be greatly appreciated.
Plunker link: https://plnkr.co/edit/e9laTBnqJKb8VzhHEBmn?p=preview
Edit
Here is my pipe:
import {Component, Inject, OnInit, Pipe, PipeTransform} from '@angular/core';
@Component({
selector: 'watchlist',
templateUrl: './watchlist.component.html',
styleUrls: ['./watchlist.component.css'],
pipes: [ ArraySortPipe ]
})
@Pipe({
name: "sort"
})
export class ArraySortPipe implements PipeTransform {
transform(array: Array<string>, args: string): Array<string> {
array.sort((a: any, b: any) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return array;
}
}
Simply add the pipe
name to the html file:
<tr *ngFor="let elem of values | sort">