Creating a map based on data retrieved from a JSON response

I am currently faced with an issue involving data retrieved from an API in JSON format, where the entries are structured as maps with number keys. Due to this structure, I am unable to assign my result to the data structure below due to missing Map methods.

entryContainer = {
    entries: {
        1: {
            title: 'title 1'
        },
        2: {
          title: 'title 2'
        }
}

export interface EntryContainer {
    entries: Map<number, Entry>;
}

export interface Entry {
    title: string;
}

// The current assignment does not work
let result: EntryContainer = entryContainer;

Could anyone suggest a more elegant approach to initializing the Entrycontainer with data obtained in the aforementioned format?

Answer №1

The content in the information you're receiving isn't structured as a Map, so it will be necessary to construct a new Map.

The great news is that this process can be easily achieved using Object.entries along with new Map:

let result: EntryContainer = {
    content: new Map(Object.entries(entryContainer.content).map(([key, value]) => [+key, value]))
};

This code snippet:

  • Utilizes Object.entries to obtain an array of [string, string] pairs.
  • Applies map to transform the array into [number, string] pairs instead. (It's important to note that keys within your entryContainer object are treated as strings, even if represented by numeric literals.)
  • Takes the resulting array of [number, string] pairs and constructs the new content map.
  • Wraps the created content map inside the EntryContainer.

Please make sure that your configurations for target and/or lib are properly set. Keep in mind that Map belongs to ES2015 while Object.entries is part of ES2017 standards.

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

Reorganizing Execution Order in AfterViewInit with Subscriptions in Angular 10

In my component, I am using the ngAfterViewInit lifecycle hook to handle certain tasks: ngAfterViewInit() { this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0); this.subscription = this.dataService.dataChanged .subscribe( ...

The error message "Unable to access property 'open' of an undefined menu" is being displayed in a TypeScript code

I am facing an issue with the action in my menu. For this project, I am using a material menu and icons. The main menu code appears as follows: <mat-menu #rootMenu="matMenu" [overlapTrigger]="false"> <ng-template matMenuContent let-element="ele ...

Guide to Setting Up "Remember Me" Login for Users in Angular

I am having trouble setting the 'Remember Me' option on my Login page. I tried using localstorage session but it seems like something is missing in the service file that's causing it not to respond properly. I attempted to follow a guide on ...

The variable <variable> is not meeting the 'never' constraint. Error code: ts(2344)

Currently, I am attempting to utilize Supabase alongside TypeScript. However, I encounter an error when trying to use functions like insert(), update(), upsert(), etc. Specifically, the issue arises when declaring the object I want to declare: "Type & ...

A guide on exposing TypeScript classes globally through a WebPack bundle in JavaScript

Currently delving into TypeScript, my aim is to gradually replace JS with TS. However, due to having numerous JS files, my strategy involves creating new classes in TS and incorporating them into my existing JS files for the time being. Eventually, I plan ...

What are some key indicators in the source code that differentiate TypeScript from JavaScript?

Reviewing some code on Github, I am looking for ways to quickly determine whether the script is written in JavaScript or TypeScript. Are there any simple tips or hints that can help with this? For instance, when examining an array declaration like the on ...

Using a template literal with the keyof operator as an interface property

Imagine a scenario where we have a basic interface: interface Schedule { interval: "month" | "day"; price: number; } We can create a template-literal type with TypeScript version 4.4: type PrefixedScheduleKey = `schedule__${keyof S ...

Dealing with side effects in react/redux: Best practices and tips

Trying to find the best way to integrate an async side-effects handler into my react/redux setup has been quite a challenge. In my react-router-driven application, all the main containers at root level are smoothly dispatching actions and receiving update ...

A guide on creating a concatenation function using TypeScript

Looking for a way in Typescript to define an interface Calculator that allows for concatenation capabilities? interface Calculator { ... } let calcu: Calculator; calcu(2).multiply(5).add(1) I attempted the following: interface Calculator { (num: n ...

Implementing React custom component with conditional typing

My goal is to enable other developers to set a click handler for a button only if the button's type is set to button. Users can only set the type to either button or submit. I want to restrict developers from setting the onClick property on the comp ...

using any class as a function parameter in TypeScript

Looking for advice: I am new to TypeScript and have classes defined like the ones below: export declare class SampleOne extends Setting { getValue(): Promise<boolean>; setValue(value: boolean): Promise<void>; } And export declare class ...

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

Exploring the concept of asynchronous subscriptions in Angular

My current issue seems to be related to asynchronous programming, specifically with the subscription not running at the desired time. I typically approach this problem from both the user's and developer's perspectives. User's Perspective: ...

Retrieve the implementation of an interface method directly from the constructor of the class that implements it

I am looking to create a function that takes a string and another function as arguments and returns a string: interface Foo { ConditionalColor(color: string, condition: (arg: any) => boolean): string; } I attempted to pass the ConditionalColor metho ...

Implementing Limited Results in Redis FT.SEARCH with TypeScript

Snippet of code: client.ft.SEARCH('license-index-json',"@\\$\\" + ".reservedForApplicationName:GSTest",{ LIMIT: { from: 0, to: 1 } }) Error message: An error occurred when trying t ...

Angular Tutorial: Understanding the Difference Between TypeScript's Colon and Equal To

I've been diving into the Angular4 tutorial examples to learn more about it. https://angular.io/docs/ts/latest/tutorial/toh-pt1.html One of the code snippets from the tutorial is as follows: import { Component } from '@angular/core'; @Co ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

"Troubleshooting a case where mongoDB's updateOne function is

I am in the process of removing certain references to objects within different sections (section1, section2, section3, others) in each file. Sample Document: { "_id": "64a3268474aa29e72b40c521", "name": "Test", ...

Difficulties in Networking Requests Following Event Emitter Notification in an Angular Application

Within my Angular application, a network request is sent to retrieve filtered data based on user-selected filters. The function responsible for handling the filter values and executing the request is outlined as follows: public onFilterReceived(values) { ...

Exploring the power of async/await and promise in TypeScript

I'm puzzled as to why the return type string in this method is showing up as a red error: exportPageAsText(pageNumber: number): string { (async () => { const text = await this.pdfViewerService.getPageAsText(pageNumber); ...