打字稿静态只读

时间:2019-07-22 05:01:04

标签: angular typescript find

我试图在我的代码中使用静态只读,但是我从来没有做过这样的事情。我知道我可以这样:

export class Names {
    static readonly michael = { firstName: 'michael', secondName: 'jackson'};
    static readonly john = { firstName: 'John', secondName: 'Doo'};
    static readonly donald = { firstName: 'Donald', secondName: 'Trump'};
}

我有

name = 'michael';

我需要在名字中搜索并找到属于michale的人,并返回其姓氏和名字

found = { firstName: 'michael', secondName: 'jackson'};

不用担心名称,因为我只是简化了有人可以帮助我的问题,没有名称,所有静态只读值都是唯一的。我知道我可以在数组内部搜索并找到,但是如何在类内部搜索?

4 个答案:

答案 0 :(得分:2)

要获取存储在Names中的所有值,可以使用Object.values。然后,您可以find必需的一个:

Object.values(Names).find(p => p.name === 'michael')

答案 1 :(得分:1)

您可以尝试使用此代码

import { Component, OnInit } from '@angular/core';
import { Names } from './models/Names';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  title = 'angular-material';
  name = 'michael';
  constructor() { }
  ngOnInit(): void {
    if (Names[this.name]) {
      console.log(Names[this.name]);
    } else {
      console.log('Not found');
    }
  }
}

答案 2 :(得分:0)

您应该使用数组类型的单个静态只读变量,该变量包含所有对象。基本上是一个对象数组:成角度的,这就是您要这样做的方式。

import { Component, OnInit } from '@angular/core';
import { Names } from './models/Names';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class Names implements OnInit {

  static readonly arrayOfObjects = [
  { firstName: 'michael', secondName: 'jackson'},
  { firstName: 'John', secondName: 'Doo'},
  { firstName: 'Donald', secondName: 'Trump'}
];
  constructor() {
  const filter = Names.arrayOfObjects.filter(object => object.firstName === 'michael')

   console.log(filter)
 }

}

答案 3 :(得分:0)

对于想要通过标签访问值的特定情况,您不必转换为对象数组并执行线性搜索(就像当前接受的答案一样)-您可以这样做

export class Names {
    static readonly michael = { firstName: 'michael', secondName: 'jackson'};
    static readonly john = { firstName: 'John', secondName: 'Doo'};
    static readonly donald = { firstName: 'Donald', secondName: 'Trump'};
}

let name = 'michael';
let found = Names[name];
console.log(found);

这会起作用,但 Typescript 会抱怨按字符串索引不适合 Names 类型。它是什么(一些缩小编译器会破坏这种行为)。

正确的答案可能是问一个不同的问题,因为使用静态只读变量的名称作为索引并没有按照预期的方式使用语言,并且以这种方式表示时可以可靠地搜索它们的唯一方法是代价高昂的线性搜索。

对相同数据的更好表示很简单

const names = {
  'michael': { firstName: 'michael', secondName: 'jackson' },
  'john': { firstName: 'John', secondName: 'Doo' },
  'donald': { firstName: 'Donald', secondName: 'Trump' },
};

然后您可以通过索引清晰正确地访问 names[firstName]。更好的方法是使用严格类型的 Map,并使用防止意外修改的实际类来表示您的数据块(即使用这些结构中的任何一种都可以执行 names['donald'].secondName = 'duck'