如何循环 Record<K, T>

sre*_*moh 7 foreach typescript

我有记录Records类型:

export interface List {
  name: string;
  title: string;
}

export type RecordType
= 'recordOne'
| 'recordTwo'
| 'recordThree';

export const Records: Record<RecordType, List> = {
  recordOne: {
    name: 'Name1',
    title: 'Ausi bere ut erit adeo enim an suae'
  },
  recordTwo: {
    name: 'Name2',
    title: 'Petebat proprie suo methodo'
  },
  recordThree: {
    name: 'Name3',
    title: 'Petebat proprie suo methodo inscitiae'
  }
}
Run Code Online (Sandbox Code Playgroud)

我想搜索具有特定文本的记录,但为了做到这一点,我需要循环遍历,Records那么你会怎么做呢?我的意思是你会怎么想Records

基本上这就是我想要的:

findMatchingTitle(myString) {
   let title = '';
   this.Records.foreach(x => {

     if(myString.includes(x.title)) {
       title = x.title;
     }
   });

  return title;
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

小智 8

一般来说,要循环对象,您可以执行以下操作:

for(let prop in obj) console.log(obj[prop])
Run Code Online (Sandbox Code Playgroud)

然而,打字稿不会让你在没有隐式任何的情况下做到这一点,这就是为什么你必须输入强制转换:

for (let prop in Records) console.log((Records as any)[prop]);
Run Code Online (Sandbox Code Playgroud)

循环访问对象并比较属性的另一种方法是使用Object.keysObject.values,如下所示

function findMatchingTitle(myString: string): string {
  for (let index in Object.keys(Records)) {
    let title: string = Object.values(Records)[index].name;
    if (title.includes(myString))
      return title;
  }
  return '';
}
Run Code Online (Sandbox Code Playgroud)

或者,对于精确搜索,它将是:

function findMatchingTitle(myString: string): string {
  for (let index in Object.keys(Records)) {
    let title: string = Object.values(Records)[index].name;
    if (title === myString)
      return title;
  }
  return '';
}
Run Code Online (Sandbox Code Playgroud)