abhi abhi - 4 months ago 152
JSON Question

How to display only unique values in the dropdown using Angular 2

I have a JSON data from which I am displaying 'accountNumber' into a dropdown using *ngFor. Since there are multiple entries in JSON data with the same account number, I am seeing the same account number multiple times in the dropdown.
enter image description here

html:

<div class="btn btn-default dropdown-toggle" type="button"
id="dropdownMenu" data-toggle="dropdown" aria-expanded="true">

<span>Select</span>
<span class="caret"></span>
<ul class="select-menu" aria-labelledby="dropdownMenu">
<li *ngFor="#account of accounts">{{account.accountNumber}}</li>
</ul>
</div>


json:

`[
{
"accountNumber": 7890,
"transactionDate": "4/2/2016",
"postingDate": "4/3/2016",
"description": "Pok Pok Thai",
"category": "Restaurants",
"amount": 15.00
},
{
"accountNumber": 7890,
"transactionDate": "4/3/2016",
"postingDate": "4/4/2016",
"description": "Pok Pok Hai",
"category": "Hotel",
"amount": 25.00
},

{
"accountNumber": 8901,
"transactionDate": "4/6/2016",
"postingDate": "4/7/2016",
"description": "Pok Pok Fai",
"category": "Dairy",
"amount": 55.00
},
{
"accountNumber": 8901,
"transactionDate": "4/7/2016",
"postingDate": "4/8/2016",
"description": "Pok Pok Aai",
"category": "Automotive",
"amount": 65.00
},

{
"accountNumber": 4567,
"transactionDate": "4/9/2016",
"postingDate": "4/10/2016",
"description": "Pok Pok Cai",
"category": "Healthcare",
"amount": 85.00
},
{
"accountNumber": 4567,
"transactionDate": "4/10/2016",
"postingDate": "4/11/2016",
"description": "Pok Pok Dai",
"category": "Healthcare",
"amount": 95.00
},

{
"accountNumber": 8901,
"transactionDate": "4/12/2016",
"postingDate": "4/13/2016",
"description": "sit amet",
"category": "Software",
"amount": 115.00
}
]`


How can I avoid displaying duplicate values of the account number in the dropdown?I am assuming it will require a custom pipe but not sure how to do that.

I am new to Angular 2 and tried looking for the solution but couldn't find anything that suits my need.

Answer

There is already post explaing basic of pipes with examples: How to apply filters to *ngFor

See the working plunker for your case http://plnkr.co/edit/zkuP3CSnjg4VI5atMCnP .. I have used lodash library and its uniqBy function, then the pipe is really that simple:

declare var _: any; // lodash, not strictly typed

@Pipe({
    name: 'uniqFilter',
    pure: false
})
@Injectable()
    export class UniquePipe implements PipeTransform {
        transform(items: any[], args: any[]): any {

        // lodash uniqBy function
        return _.uniqBy(items, "accountNumber");
    }
}

.. and the usage in your component:

<div>
    <ul>
        <li *ngFor="let account of accounts | uniqFilter">{{ account.accountNumber }}</li>
    </ul>
</div>

It shouldn't be difficult to rewrite it to more abstract version. Hope it helped.