在Angular2中找到两个键的最大值

时间:2016-07-11 14:05:45

标签: angular

我正在阅读一个包含大约500个条目的数据文件,如:

const LOCKERS: Locker[] = [
  { lockerNumber: 1, room: 'Ladies', size: 'Small'},
  { lockerNumber: 2, room: 'Ladies', size: 'Small'},
  { lockerNumber: 3, room: 'Ladies', size: 'Small'},
  { lockerNumber: 4, room: 'Ladies', size: 'Small'},
  { lockerNumber: 1, room: 'Ladies', size: 'Large'},
  { lockerNumber: 2, room: 'Ladies', size: 'Large'},
  { lockerNumber: 3, room: 'Ladies', size: 'Large'},
  { lockerNumber: 1, room: 'Gents', size: 'Small'},
  { lockerNumber: 2, room: 'Gents', size: 'Small'},
  { lockerNumber: 3, room: 'Gents', size: 'Small'},
  { lockerNumber: 1, room: 'Gents', size: 'Large'},
  { lockerNumber: 2, room: 'Gents', size: 'Large'},
  { lockerNumber: 3, room: 'Gents', size: 'Large'},
  { lockerNumber: 4, room: 'Gents', size: 'Large'}
];

我的服务是这样的:

import { Injectable } from '@angular/core';
import { Locker } from './locker';
import { LOCKERS } from './mock-lockers';

@Injectable()
export class LockerService {
    getLockers() {
        return Promise.resolve(LOCKERS);
    }
}

我的组件:

import { Component } from '@angular/core';
import { Locker } from './locker';
import { LockerService } from './locker.service';

@Component({
  selector: 'my-app',
  templateUrl: './app/app.locker.html',
  providers: [LockerService]
})

export class AppComponent {
  title = 'The lockerrooms';
  lockers: Locker[];
  ladiesSmall: number;
  ladiesLarge: number;
  gentsSmall: number;
  gentsLarge: number;

  constructor(
    private lockerService: LockerService

  ) { }

  getLockers() {
    this.lockerService.getLockers()
      .then( data => this.lockers = data)
  }

  ngOnInit() {
    this.getLockers();
  }
}

我正在寻找一种方法来获得每个房间大小组合的最大lockerNumber。 例外结果 -

MaxLadiesSmall 4
MaxLadiesLarge 3
MaxGentsSmall 3
MaxGentsLarge 4

1 个答案:

答案 0 :(得分:0)

对于这样的操作, Lodash 库及其chaining ability是完美的。此外,代码几乎可以重复使用。

试试这个:

var gentsSmallMaximum = _(LOCKERS)
    .filter(locker => locker.room === 'Gents' && locker.size === 'Small')
    .map(locker => locker.lockerNumber)
    .max();

只需导入库

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js"></script>

如果你想要TypeScript版本,你可以使用明确输入:

https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/lodash

然后将它放在@Component之前,强制TypeScript编译:

declare var _: any;