Efficient Searching with Typescript and Lodash: Boosting Performance with Arrays and Objects

I am faced with the challenge of converting between two classes called MyObject and MyObjectJSON, which have helper methods to assist in the conversion process: myObj.toJSON() and MyObject.fromJSON().

Currently, I have instances of these classes represented in two different constructs that need to be converted back and forth:

  1. A mapping of MyObject instances where the keys are based on their id property: { [id: number]: MyObject }
  2. A list containing instances of MyObjectJSON: MyObjectJSON[]

Seeking guidance on how to efficiently convert between these two structures using the lodash library.

Answer №1

const objectMap: { [id: number]: MyObject } = {};
objectMap[obj1.id] = obj1;
objectMap[obj2.id] = obj2;
objectMap[obj3.id] = obj3;
// {
//   1: MyObject,
//   2: MyObject,
//   3: MyObject
// }

let JSONMap: { [id: number]: MyObjectJSON };
JSONMap = lodash.mapValues<MyObject, MyObjectJSON>(objectMap, item => item.toJSON());
// {
//   1: MyObjectJSON,
//   2: MyObjectJSON,
//   3: MyObjectJSON
// }

let JSONList: MyObjectJSON[];
JSONList = lodash.map<MyObject, MyObjectJSON>(objectMap, item => item.toJSON());
// [ MyObjectJSON, MyObjectJSON, MyObjectJSON ]

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

The specified property cannot be found in the type 'IntrinsicAttributes & ...'

I'm currently working on adding a custom prop to a custom styled-component: interface Props { image?: string; title?: string; subtitle?: string; background?: string; } export function CardWide({ image, title, subtitle, background }: Props) ...

Tips for patiently anticipating the completed response within an interceptor

Using the interceptor, I want to display a loading spinner while waiting for subscriptions to complete. This approach works well in individual components by showing and hiding the spinner accordingly: ngOnInit() { this.spinnerService.show(); this. ...

Exploring the functionality of the Angular snackbar feature

I have created a simple snackbar with the following code: app.component.ts: ngOnInit(){ this.dataService.valueChanges.pipe( filter((data) => data === true), switchMap(() => { const snackBarRef = this.matSnackBar.open ...

Developing React components with Typescript requires careful consideration when defining component props, especially when the component may be

Consider the following scenario: { this.props.userName && <UserProfile userName={this.props.userName} /> In the UserProfile component: interface UserProfileProps { userName: string; } class UserProfile extends React.Component<UserProfile ...

Using Array.push within a promise chain can produce unexpected results

I have developed a method that is supposed to retrieve a list of devices connected to the network that the client has access to. export const connectedDevicesCore = (vpnId: string, vpnAuthToken: string) => Service.listVPNConnectionsCore ...

How can I update the image source using Angular?

<div class="float-right"> <span class="language dashboard" data-toggle="dropdown"> <img class="current" src="us-flag.png" /> </span> <div class="dropdown dashboar ...

Can TypeORM create an entity for a many-to-many relationship that functions like ActiveRecord's join table concept?

Consider a scenario where there is a Guardian entity connected to a Student entity. The goal is to establish their many-to-many relationship in TypeORM by introducing a new entity called StudentGuardianRelationship. This intermediary entity serves the purp ...

When using Angular 10 or later, the mouseclick event will consistently trigger Angular's change detection mechanism

When I bind an event to elements on a component's HTML page, the component continues to detect changes even when the element event is fired. Despite setting the change detection mode of the component to OnPush, this behavior persists. To test this, I ...

clicking a table row will activate the *ngFor directive

Incorporating data from an API into a table, I have enabled the functionality for users to click on table rows in order to change the displayed data using background code: <tr [ngClass]="tablerowClass" *ngFor="let dataObject of data$ | async" (click)=" ...

Generate TypeScript type definitions for environment variables in my configuration file using code

Imagine I have a configuration file named .env.local: SOME_VAR="this is very secret" SOME_OTHER_VAR="this is not so secret, but needs to be different during tests" Is there a way to create a TypeScript type based on the keys in this fi ...

Showing error messages in Angular when a form is submitted and found to be invalid

My form currently displays an error message under each field if left empty or invalid. However, I want to customize the behavior of the submit button when the form is invalid. <form #projectForm="ngForm" (ngSubmit)="onSubmit()"> ...

What is the process for setting up custom global interfaces in TypeScript using .d.ts files?

I'm currently facing an issue in my ReactJS project using Webpack2 and TypeScript. Everything is functioning perfectly except for one thing - I've been struggling to move my self-written interfaces into separate files so they are accessible throu ...

Generate a new data structure by pairing keys with corresponding values from an existing

Imagine having a type named Foo type Foo = { a: string; b: number; c: boolean; } Now, I am looking to create a type for an object containing a key and a value of a designated type T. The goal is for the value's type to be automatically determin ...

Implementing various custom validation techniques in Angular 2

I am encountering an issue with adding multiple custom validations to a form. Currently, I am only able to add a single custom validation to my form. How can I include multiple validations? For example: this.user = this.fb.group({ name: ['', ...

Enhancing the loading speed of hefty Angular components

The issue I encountered involved a large component that loads over 1000 data elements, populated by a service called only once. Initially, the service was being called each time the component initialized, which seemed to be causing performance problems. To ...

Monitoring User Interactions for Maintaining Session Foresight Plan utilizing RxJS

My goal is to maintain user session activity by implementing a system that locks an interactive session after 15 minutes of user inactivity (defined as no keyboard or mouse activity). The information system will automatically lock the session if there is ...

The custom error page in NextJS is failing to display

In my custom pages/404.ts file, I have coded the following: export default function NotFound() { return <h1>404 - Page Not Found</h1> } Additionally, there is another page that displays a 404 error when the organization is null: import Error ...

`When attempting to use Typescript with Electron, the error 'exports is not defined

Trying to launch my basic electron application, I utilize Typescript for development which then compiles into JavaScript. However, upon running the app, an error is encountered: ReferenceError: exports is not defined[Learn More] file:///Users/ahmet/Docume ...

The submit button seems to be unresponsive or unreactive

As a newcomer to Angular 2 and Typescript, I am in the process of building a web application. I have created several input fields and, following user submission via a button, I want to log the inputs to the console. However, it seems like my button is not ...

Printing values of an object in an Angular/HTML script is proving to be quite challenging for me

In my Angular project, I have created a service and component for listing objects. The list is functioning correctly as I have tested it with 'console.log()'. However, when I try to display the list on localhost:4200, nothing appears. <table&g ...