typescripttypescript-utility

How to filter on the props of the Record<K, T>


Say I have this record:

export const MenuData: Record<Header, HeaderInfo> = {
  val1: {
    message: 'xyz',
    buttonText: 'txt',
    buttonUrl: '/url-abc',
  },
  val2: {
    message: 'xyz123',
    buttonText: 'txt4',
    buttonUrl: '/url-1abcd',
  },
  ... 
}

I want to filter/find the MenuData record based on buttonUrl property.
Something like MenuData.filter(buttonUrl === '/url-1abcd')
So in that case would return the whole val2 object

Is there anyway to achieve that?


Solution

  • You can call Object.values on the object which will return an array of the values of the keys, then use .find to find the object you need based on the condition

    const obj = Object.values(MenuData).find(obj => obj.buttonUrl === '/url-1abcd')