Transforming a JSON file that has been previously converted to an Observable into a TypeScript map within an Angular application

There is a json data file named dummy, with the following structure:

[
    {"key":"KEY1", "value":["alpha","beta","gamma"]},

    {"key":"KEY2", "value":["A","B","C"]},

    {"key":"KEY3", "value":["One","Foo","Bar"]}
]

The goal is to convert this json file into a map with key-value pairs matching the structure of the json file.

To accomplish this task, an observable named myObservable was created. Below is an example code snippet from the component.ts file:

myMap: any = {};
myObservable: Observable<any> = Observable.of(this.dummy);

getObservable() {
    return this.myObservable;
}

ngOnInit() {
    this.getObservable()
    .subscribe(myResponse => {
        this.myMap = new Map(myResponse); //Converting myresponse to map here.
    )}.

Unfortunately, the above approach did not work as intended. How can I correctly convert this observable object to a map in TypeScript?

Desired Output:

{
    Key1,[alpha,beta,gamma]
    Key2,[A,B,C]
    Key3,[One,Foo,Bar]
}

Answer №1

const exampleData = [

     {"key":"KEY1", "value":["apple","banana","cherry"]},

     {"key":"KEY2", "value":["X","Y","Z"]},

     {"key":"KEY3", "value":["First","Second","Third"]}
 ]
 
 const finalResult = new Map();
 
 exampleData.map(element => {

 finalResult.set(element["key"], element["value"]);
 })
 
for (var [key, value] of finalResult.entries()) {
  console.log(key + ' = ' + value);
}

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

Encountering an "undefined is not a function" error across all libraries

While working on ASP.Net MVC4, I have encountered an issue where I consistently receive the error message "undefined is not a function" when using jQuery functions with different libraries. Despite ensuring that every ID is correct and everything has bee ...

Display validation in HTML5 only when the form is submitted

Here is the code snippet I am referring to: <input required pattern="[0-9]{5,10}" oninput="setCustomValidity('')" oninvalid="setCustomValidity('Type something')" /> I'm looking for a way to remove o ...

In search of the most efficient method for integrating an AJAX-powered TreeGrid feature

Can anyone recommend an Ajax/TreeGrid implementation that meets the following criteria: Must support server side sorting Should be able to load leaf nodes on demand, meaning only children of open nodes are loaded Needs to support paging so that nodes are ...

Angular: utilizing a ng-false-value function

Within my Angular application, I have a series of checkboxes generated using a nested ng-repeat: <div ng-repeat="partner in type.partners"> <label class="checkbox-inline"> <input type="checkbox" ng-model="partners[$paren ...

Transmitting an array through a query parameter from Angular 6 to PHP

Hey there! I'm currently in the process of setting up an Angular application to make a GET request to my PHP backend. The PHP code is set up to expect three parameters - two strings and an array of strings. For example, it would look something like th ...

SmartEdit functions properly when spartacus is running using yarn start --ssl, but does not work without SSL enabled

I followed the smartedit setup instructions at and everything works well when I start the Spartacus server with yarn start --ssl. However, if I start the server with just yarn start, the storefront does not appear. See image here for reference ...

What is the best way to define a global variable in TypeScript and access it throughout a Vue application?

In my main.ts file, I am looking to define a variable that can be accessed in all Vue files. Within my sfc.d.ts file, the following content is included: declare module '*.vue' { import Vue from 'vue' export default Vue } declar ...

Guide on converting this function into a computed property within Vue

Is it possible to concatenate a fixed directory path, which is defined in the data property, with a file name that is determined using v-for? I encountered an issue when attempting to do this using a computed property. The error message displayed was: ...

Conditional rendering of a component in ReactJS while maintaining the "empty" space

Is there a way to conditionally render a component without affecting the layout of other components? I'm trying to avoid unwanted shifts caused by this div Do you have any suggestions? Here is a snippet of my code: const [displayFeedbackMessage, s ...

Crafting Effective AngularJS Directives

Recently, I've been delving into AngularJS and have grasped the core concepts quite well. As I embark on building my own application, I find myself struggling with laying out the blueprint, particularly in terms of directive design. Are there any not ...

When setupFilesAfterEnv is added, mock functions may not function properly in .test files

Upon including setupFilesAfterEnv in the jest.config.js like this: module.exports = { preset: 'ts-jest', testEnvironment: 'node', setupFilesAfterEnv: ["./test/setupAfterEnv.ts"] } The mock functions seem to sto ...

Grab the source attribute of the <img> tag (identified by class) across numerous HTML pages

Here is an example: A website has the URL , where xxxx represents an integer between 1 and 1935. On each page, there may be an <img class="thumbnail" src="Images\Robots\{robotname}.png">. However, not all pages have th ...

When the document is shifted by an angular function call, the mouseup event fails to trigger

My problem involves an angular function that alters the ng-if state to display the sidebar when the image is clicked. However, upon calling the function and shifting the entire webpage, the mouseup event for the image no longer triggers when I release th ...

Automatic Full-Screen Switching Upon Video Playback in HTML5

Currently, I have a video clip set to play when the timer reaches a certain point. My goal is for the video to automatically enter full-screen mode when it starts playing and return to its original position when it stops, as the timer will continue ticking ...

Implementing queuing functionality in Angular's HttpClient

I am facing a similar requirement that was discussed in Add queueing to angulars $http service, but I am looking for an implementation in Angular 4.3 or 5 using the HttpInterceptor from @angular/common/http. The API I am working with has some unique limit ...

Using Postman to transmit a JSON API object

I'm currently utilizing the JSONAPI Specification from Here is an example of the data I have: { "data": { "type": "tag", "id": "1", "attributes": { "name": "Test" } } } Is there a way to send a post request to the e ...

The value of a checkbox in Angular 10 is coming out as undefined

Within my component, I set up the formGroup as shown below: constructor(private apiService: ApiService) { this.form = new FormGroup({ product: new FormControl(), shops: new FormGroup({}) }); } When selecting a vendor from a drop-do ...

Create a VueJS/VuetifyJS implementation inspired by the WhatsApp swipe between tabs animation

Currently, I am utilizing the VuetifyJS framework for VueJS and I am interested in replicating the swipe between tabs transition seen in WhatsApp for Android. In WhatsApp, you have the ability to swipe left or right to view a new section as you swipe. Vue ...

TS type defined by JS constants

I am currently working on a project that involves both JavaScript and TypeScript. I am trying to find a solution to reduce code duplication when using JavaScript string constants by converting them into TypeScript types. For example, let's say I have ...

Unable to locate element in the DOM using XPath

Having trouble retrieving an element from the DOM using XPath <input bsdatepicker="" class="form-control font-size-normal ng-untouched ng-pristine ng-valid" id="endDate" name="endDate" placement="top" type="text"> The value of the element is not p ...