How to loop though Record<K, T>

橙三吉。 提交于 2021-02-11 17:00:28

问题


I have Records type of Record:

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'
  }
}

I want to search for record with specific text but in order to do that I need to loop through the Records so how would you do that? I mean how would you loop thought the Records ?

Basically that is what I want:

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

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

  return title;
}

Any ideas?


回答1:


Generally to loop through Objects you can do:

for(let prop in obj) console.log(obj[prop])

However typescript wont let you do that with no implicit any, which is why you'd have to type cast:

for (let prop in Records) console.log((Records as any)[prop]);

Another way to loop through an Object and compare properties is with Object.keys and Object.values as shown below

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 '';
}

Alternatively, for an exact search it would be:

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 '';
}



回答2:


Not really related to TS, in order to search for the title, I would first get the records values as array, and use the Array.find to look for the title.

if I found one, I will get its title

const records = {
  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'
  }
}

const findMatchingTitle = str => Object.values(records).find(record => record.title.includes(str))?.title

console.log(findMatchingTitle("inscitiae"))


来源:https://stackoverflow.com/questions/61205772/how-to-loop-though-recordk-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!