Tuesday, July 5, 2016

JavaScript's C# SelectMany

C# has a convenient method for flattening collections' collection, that method is SelectMany:

var result = 
    from account in areas.SelectMany(area => area.Accounts)
    where account.Selected
    select account.AccountId;



In JavaScript:

interface IAccountDto
{
    accountId: number;
    accountName: string;

    selected?: boolean; // not in actual DTO, just used in UI
}

interface IAreaDto
{
    areaName: string;
    accounts: IAccountDto[];
}



class Something {

   
    areas: IAreaDto[] = [
            {
                areaName: "Philippines",
                accounts: [
                    {
                        accountId  : 168,
                        accountName: "Account 168",
                        selected: true
                    },
                    {
                        accountId  : 169,
                        accountName: "Account 169",
                        selected: true
                    },
                ]
            },
            {
                areaName: "China",
                accounts: [
                    {
                        accountId  : 170,
                        accountName: "Account 170"
                    },
                    {
                        accountId  : 171,
                        accountName: "Account 171",
                        selected: true
                    },
                ]
            },


        ];   
   
   
   getResult(): number[] {

       let result = 
            this.areas.map(ar => ar.accounts)
            .reduce((a,b) => a.concat(b), [])
            .filter(ac => ac.selected)
            .map(ac => ac.accountId)
            
       return result;
   }
}



let s = new Something();

let x = JSON.stringify(s.getResult());

document.body.innerHTML = x;

Happy Coding!

No comments:

Post a Comment