Tips for sorting through the properties of the Record<K, T>:

Let's say we have the following data stored in a record:

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

We are looking to filter or find specific entries in the MenuData record based on their buttonUrl property value.
For example, running

MenuData.filter(buttonUrl === '/url-1abcd')
should return the entire object under val2

Is there a way to achieve this functionality?

Answer №1

To retrieve the values of keys in an object, you can utilize Object.values method. This will give you an array of values which you can then search through using .find to locate the specific object based on certain conditions.

const desiredObj = Object.values(DataMenu).find(obj => obj.key === '/specific-url')

Answer №2

I encountered a similar issue. Here is my approach to returning key-value pairs for navigation.

1. Key-Pairs

export type PagePath =
  ...
  '/demos' |
  '/demos/hr-browser-scroll' |
  '/demos/grid/filter-management' |
  '/';

2. Mapping Dictionary

export const pagePath2PageInfoDict: Record<PagePath, PageInfo> = {
  ...
  '/demos': new PageInfo('demos'),
  '/demos/hr-browser-scroll': new PageInfo('demos', 'horizontal browser scroll'),
  '/demos/grid/filter-management': new PageInfo('demos', 'grids: filter management'),
  '/': new PageInfo(),
};

3. Retrieve Key-Value Pairs

export function getPagePath2PageInfoPairs(predicate: (path: string) => boolean = () => true) {
  return Object.keys(pagePath2PageInfoDict)
    .filter(predicate)
    .map(key => {
      const path = key as PagePath;
      const item: IPageNavItem = {
        path,
        info: pagePath2PageInfoDict[path],
      };

      return item;
    });
}

4. Implementation Example

export class DemosComponent extends PageCoreComponent {
  readonly navItems = getPagePath2PageInfoPairs(p => p.startsWith('/demos/'));
}
<nav *ngFor="let navItem of navItems; index as i">
  <div class="nav-item"
       [routerLink]="navItem.path"
       routerLinkActive="active"
  >
    <div>{{ navItem.info.pageTitle }}</div>
  </div>
</nav>

https://i.stack.imgur.com/lhkVj.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

add headers using a straightforward syntax

I'm attempting to append multiple header values. This is what I'm currently doing: options.headers.append('Content-Type', 'application/json'); options.headers.append('X-Requested-By', 'api-client'); ... ...

Having trouble locating the name WebGLObject in my TypeScript code

Every time I try to run ng serve command An error pops up on my screen saying: "WebGLObject cannot be found." ...

What is the best way to integrate model classes within an Angular module?

I have a few classes that I want to keep as plain bean/DTO classes. They are not meant to be display @component classes, @Pipe classes, or @Directive classes (at least, that's what I believe!). I am trying to bundle them into a module so that they ca ...

The click event triggered by the onclick clone/function may not always activate the click handler

As a newcomer in the JavaScript domain, I am encountering an issue where the first clone created after clicking 'add more' does not trigger my click me function. However, every subsequent clone works perfectly fine with it. What could be causing ...

Accessing Nested Arrays in Angular 8: Retrieving Data in HTML Template from Multiple Layers of Arrays

Hello there. I'm using an API that gives me the following data: (4) [{…}, {…}, {…}, {…}] 0: dueDate: "2018-03-26T00:00:00" priority: {priorityId: 1, priorityName: "Critical", priorityColor: "red"} statuses: Array(1) 0: ...

When attempting to utilize TypeScript with Storybook, Jest may encounter an error stating, "Incompatible types for property 'id'."

Currently, I'm exploring the use of stories in my unit tests with Jest + RTL to reduce redundancy. However, I've encountered an error stating "Types of property 'id' are incompatible" when passing arguments that are also used in my stor ...

Just completed the upgrade of my Angular project from version 9 to version 12, but now encountering issues with a module that utilizes Plotly

Here is the content of my app module file. All components and imports are in their respective places as specified in the documentation: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from &apos ...

Converting a string to a number in an Angular template

Within my select box, I am capturing the selected value and binding it to the variable startingYear. However, I need the type of startingYear to be a number, but it is currently registering as a string. Is there a way to convert it to a number? console ...

An error occurred while defining props due to a parsing issue with the prop type. The unexpected token was encountered. Perhaps you meant to use `{`}` or `}`?

const dataProps = defineProps({ selectedData: <Record<string, string>> }); Under the closing bracket, there is a red line indicating: Error: Unexpected token. Consider using {'}'} or &rbrace; instead?eslint Expression expecte ...

Centering on request, Google Maps adjusts its view to focus on

When I select a row, I want to set the map center to the provided coordinates in Primeng. The issue is that while this.options works fine in ngOnInit, it doesn't work when called in the showCords() function. Below is my code: gmap.component.ts im ...

Error: 'ngForOf' is not recognized as a valid property of the 'tr' element

Since this afternoon, I've been facing a challenge that I can't seem to grasp. The issue lies within a service I created; in this file, there is an object from which I aim to showcase the data in a loop. An error message is displayed: NG0303: C ...

What are some methods to troubleshoot $injector type errors in TypeScript?

I'm currently facing an issue with my AngularJS code. Here is a snippet of what I have: this.$injector.get('$state').current.name !== 'login' But, it's giving me the following error message: error TS2339: Property 'c ...

What methods are available for utilizing a runtime variable that TypeScript is unaware of?

I am looking to implement a global variable in TypeScript that will be defined dynamically at runtime. This global variable is necessary for transferring configuration properties from the server-side language to JavaScript. My approach involves using TypeS ...

Tips for Maintaining User Data Across Pages in React using React-Router-Dom and Context

I've been tackling the login functionality of a client-side application. Utilizing React alongside TypeScript, I've incorporated react-router-dom and Context to manage the user's data when they log in. However, upon refreshing the page, the ...

Learn how to automatically display a modal upon loading a webpage by simply entering the URL of the specific template

Is there a way to trigger the modal pop-up by simply typing a URL link without the need for any click function? I am currently attempting to display the modal without requiring a login, but when I type the URL, the modal appears briefly and then disappears ...

Learn how to connect a formArray from the parent component to the child component in Angular with reactive forms, allowing you to easily modify the values within the formArray

In my parent component, there is a reactive form with controls and a form group. When the user selects a playerType from a dropdown menu, I dynamically add a formArray to the formGroup. This form array will contain either 2 or 3 form groups based on the p ...

Expanding Classes through Index signatories

My attempt at creating an abstract class is not going as smoothly as I hoped. I suspect my limited knowledge of TypeScript is the primary issue, even though this seems like a common scenario. The abstract class I'm working on is called Program. It co ...

Unable to bind to ngModel as it returned as "undefined" in Angular 8

Whenever I bind a property to ngModel, it consistently returns undefined <div> <input type="radio" name="input-alumni" id="input-alumni-2" value="true" [(ngModel) ...

Tips for retrieving items from <ng-template>:

When the loader is set to false, I am trying to access an element by ID that is located inside the <ng-template>. In the subscribe function, after the loader changes to false and my content is rendered, I attempt to access the 'gif-html' el ...

Exploring Angular 7: Understanding the HTML5 Fullscreen API and Overcoming Errors

I am currently using Angular 7 and I am trying to implement a fullscreen button in my app. I have utilized the HTML5 Fullscreen API and created two functions for this purpose: openfullscreen() { // Trigger fullscreen console.log('gg'); ...