angular keyvalue pipe sort properties / iterate in order

前端 未结 11 920
有刺的猬
有刺的猬 2020-11-29 21:01

When using the Angular keyvalue pipe to iterate over an object\'s properties as follows:

相关标签:
11条回答
  • 2020-11-29 21:34

    You can keep the original order by simply setting the keyvalue pipe to an empty object {}

    *ngFor="let property of collection | keyvalue: {}"
    
    0 讨论(0)
  • 2020-11-29 21:36

    To keep the object order you can use

    keepOrder = (a, b) => {
        return a;
    }
    

    Let's say you have

    wbs = {
    "z": 123,
    "y": 456,
    "x": 789,
    "w": 0#*
    }
    

    If you use keyvalue you get alphabetical order by key

    w 0#*
    x 789
    y 456
    z 123
    

    applying :keepOrder you keep object order

    <ion-item *ngFor="let w of wbs | keyvalue: keepOrder">
        <ion-label>{{ w.key }}</ion-label>
        <ion-label>{{ w.value }}</ion-label>
    </ion-item>
    
    0 讨论(0)
  • 2020-11-29 21:42

    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

    <div *ngFor='#item in object | values:"keyName":true'>...</div>
    
    0 讨论(0)
  • 2020-11-29 21:43
    <div *ngFor="let item of object | keyvalue: 0">
      {{item.key}} : {{item.value}}
    </div>
    

    directly write and you will get the data in sameorder as it is in the json

    keyvalue: 0
    
    0 讨论(0)
  • 2020-11-29 21:48

    Yes, by default the keyvalue pair sorting data in ascending order.

    To keep it unsorted modify as:

    keyvalue: 0
    

    Final code:

    <div *ngFor="let item of object | keyvalue:0">
      {{item.key}}:{{item.value}}
    </div>
    

    But for angular 7 or above, you need to put an empty function to keep data unsorted.

    <div *ngFor="let item of object | keyvalue: unsorted">
          {{item.key}}:{{item.value}}
        </div>
    

    In your .ts file just put this empty function.

      unsorted() { }
    

    Hope it's helpful.

    0 讨论(0)
提交回复
热议问题