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

Bring in all subdirectories dynamically and export them

Here is what I currently have: -main.js -routeDir -subfolder1 -index.js -subfolder2 -index.js ... -subfolderN -index.js Depending on a certain condition, the number of subfolders can vary. Is there a way to dynam ...

Guide on implementing a .catch method in Firebase's onSnapshot function

I have recently developed an Ionic Firebase chat application. I seem to be encountering an issue with setting up a query snapshot when initializing the message page. Here is the code snippet that I am using: ngOnInit() { this.messageService.getA ...

Issue with Angular 2 Observable testing: Trying to use setInterval in an async zone test is not allowed

I am currently in the process of testing a component that relies on a service for making asynchronous HTTP calls. The service returns an Observable, which is then subscribed to by the component. Snippet from the service code: getRecentMachineTemperatures ...

Navigating through the exported components of a module without explicit type declarations

So I'm in the process of developing a module with sub-modules for Angular. Here's the notation I'm using: module App.services { export class SomeService { } } When initializing all services, I use the following code snippet: function ...

Error encountered in Angular Html2Pdf: Unable to assign the 'adoptedStyleSheets' attribute on 'ShadowRoot' due to DOMException

Looking for assistance in implementing html2pdf with Angular 12 to convert specific parts of an HTML page into a downloadable PDF. ERROR MESSAGE An error occurred while trying to execute the code: index-7a8b7a1c.js:150 Uncaught (in promise) DOMExce ...

Error message: "Mismatched data types in Formik errors when utilizing TypeScript"

I have a customized input component for formik which includes an error label if one exists. When I print it like this: {errors[field.name]}, it works. However, {t(errors[field.name]?.toLocaleString())} does not work. import { FieldProps, FormikErrors } ...

Tips for implementing <mat-progress-bar> in .ts file when making API service requests with Angular

I'm currently utilizing an API call to retrieve an image from a service, and I would like to display a progress bar while the image is being fetched. It seems that I need to incorporate the progress bar within the service as the image data is returned ...

How can I compel npm to resolve dependencies flatly?

I am working on a project where multiple frontends share a common library. The module dependencies for these projects are managed using npm. In the package.json file of each project, I specify: "dependencies": { "mylib": "file:../<...path...> ...

Error message: Unable to access property 'post' from undefined - Angular 2

Here is the snippet of code in my component file: import { Component, Injectable, Inject, OnInit, OnDestroy, EventEmitter, Output } from '@angular/core'; import { Http, Response, Headers, RequestOptions } from '@angular/http'; import & ...

Removing a value from a hashmap using Typescript - what is the best way to do it?

After successfully implementing a hashmap in typescript following a helpful post, I am facing an issue with removing something from the hashmap. TypeScript hashmap/dictionary interface To add a key to the keys field of my abstract Input class's hash ...

Get the @types definition installed from a forked repository

Background Information I recently made a workaround for a single type definition in my fork of DefinitelyTyped. This fix is located on a specific branch within my fork. It's important to note that this fix is temporary and should not be merged back ...

There is an issue with the hook call while trying to establish a context with a reducer

I am facing an issue while setting up the AppProvider component that utilizes a context and reducer to manage global data for my application. The problem seems to be arising from the useReducer hook used within the AppProvider. I have checked the error mes ...

Unrestricted Angular Audio Playback without CORS Restrictions

I am currently developing a web application using Angular4 that will include the feature of playing audio files. Unfortunately, I am facing an issue where I do not have control over the server serving the media files, and therefore cannot make any modifica ...

What is the rationale behind placing the CSS outside of the React function components, near the imports?

Recently, I encountered an issue with loading CSS inside a React function component using Material UI. Even though I managed to resolve it, I am still intrigued by the underlying reason. Initially, I had something like this setup where I placed both makeSt ...

Injecting singletons in a circular manner with Inversify

Is it possible to use two singletons and enable them to call each other in the following manner? import 'reflect-metadata'; import { Container, inject, injectable } from 'inversify'; let container = new Container(); @injectable() cla ...

Monitoring changes within the browser width with Angular 2 to automatically refresh the model

One of the challenges I faced in my Angular 2 application was implementing responsive design by adjusting styles based on browser window width. Below is a snippet of SCSS code showing how I achieved this: .content{ /*styles for narrow screens*/ @m ...

Retrieving data for a route resolver involves sending HTTP requests, where the outcome of the second request is contingent upon the response from the first request

In my routing module, I have a resolver implemented like this: { path: 'path1', component: FirstComponent, resolve: { allOrders: DataResolver } } Within the resolve function of DataResolver, the following logic exists: re ...

Is it feasible to access and modify local files within an Angular project using TypeScript code in the angular component.ts file? If so, how can this be achieved?

My Angular application is built on version 4 or higher. I have a setup in my project where there is a folder containing a txt file and another folder next to it with an angular component.ts file: FolderWithFile -----file.txt ComponentFolder -----person.co ...

What is the best approach for filtering a nested array in this scenario?

Here is the response I am getting: let m = [ { name: 'Summary', subListExpanded: false, subList: [ ] }, { name: 'Upload', subListExpanded: false, subList: [ ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...