When using the Angular keyvalue pipe to iterate over an object\'s properties as follows:
Yes, Object
properties iterates randomly since it doesn't get stored as array
in memory. However you can sort by properties.
If you want to iterate by insertion position, you need to create one extra property like index
and set the timestamp
and sort by index
.
Below is the pipe you can use to control the sorting and iteration
Pipe
import {Pipe, PipeTransform} from 'angular2/core';
@Pipe({name: 'values'})
export class ValuesPipe implements PipeTransform {
transform(value: any, args?: any[]): Object[] {
let keyArr: any[] = Object.keys(value),
dataArr = [],
keyName = args[0];
keyArr.forEach((key: any) => {
value[key][keyName] = key;
dataArr.push(value[key])
});
if(args[1]) {
dataArr.sort((a: Object, b: Object): number => {
return a[keyName] > b[keyName] ? 1 : -1;
});
}
return dataArr;
}
}
Usage
...