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

Concealing a division element if there is no content inside of it

As a newcomer to jQuery, I am experimenting with setting up a code that hides a div when the 'innerHTML' is null. However, my attempt using the code below is not working. Can anyone point out where I might be going wrong? if (($("#php-errors").h ...

The exploration of child routes and modules

I'm currently working on a somewhat large project and I've decided to break it down into modules. However, I'm facing an issue with accessing the routes of admin.module.ts. In my app.module, I have imported the admin Module. imports: [ Br ...

Tips for eliminating white frames or borders on the Mapbox canvas map

In my current project using Angular 10, I have integrated Mapbox to display path routes. Following the standard Angular practice of splitting components, I separated the map rendering component and called it into the main map component. However, I encounte ...

Navigate through Angular Material rows by utilizing the up and down arrow keys

I customized my mat-table by adding an ngclass to make the rows clickable. Now, I want to enable users to navigate using the arrow keys. Referring to this GitHub issue (https://github.com/angular/components/issues/14861), I managed to make it work initiall ...

Transform CI_Model into JSON format and then forward it to AJAX communication

How can I convert an object to JSON using json_encode and then send this JSON to AJAX as a response? Custom Code Example : <?php class CustomResponse extends CI_Model { private $status; private $data; public function __construct() { ...

What purpose does sending null to XMLHttpRequest.send serve?

Have you ever wondered why send is often called like this? xhr.send(null) instead of just xhr.send() ? W3, MDN, and MSDN all mention that the argument is optional. Additionally, the ActiveX control seems to work without it: hr=pIXMLHTTPRequest.Create ...

What is the most effective method for sorting through vast amounts of data with Javascript, React, and Redux?

Currently, I am working with a minimum JSON data set of 90k [...] and utilizing the .filter method. Everything is functioning correctly without any issues, however, from a performance standpoint, I am curious about potential improvements. Any suggestions o ...

Learn how to utilize the import functionality in Node.js by importing functions from one .js module to another .js module. This process can be seamlessly integrated

Hey there! I'm currently facing a challenge where I need to import a function from one JavaScript file to another. Both files are on the client side in Node.js, so I can't use the require method. If I try to use the import statement, I would need ...

Is it possible to send an AJAX request to a Django view that might result in a redirect?

Query I encountered an issue while attempting to access a specific Django view through AJAX. This particular view redirects users if they haven't authorized the site with Google. I suspect the problem arises from redirecting "within" a view requested ...

Interactive loadChild components

I've been attempting to dynamically import routes from a configuration file using the following code snippet: export function buildRoutes(options: any, router: Router, roles: string[]): Routes { const lazyRoutes: Routes = Object.keys(options) ...

Presenting SQL information in a hierarchical Angular grid for easy visualization

As a newcomer to Angular, I have a requirement to display data in a multilevel/hierarchical Angular Grid. The data is retrieved from a SQL Database using a query with arguments provided in the where clause. Some questions that come to mind are: Is there ...

Offset the CDK Menu

Is it possible to adjust the position of the trigger using the CDK overlay by setting an offset (e.g. cdkConnectedOverlayOffsetY)? I've looked through the CDK menu documentation but couldn't find a similar functionality. Is there a method to achi ...

modifying the appearance of the play button through a JavaScript event without directly altering it

I am currently working on building a music player from scratch using HTML, CSS, and JavaScript only. To store the list of songs, I have created an array named "songs" with details such as song name, file path, and cover image path. let songs = [ {songNa ...

Adding cache to Observable in mat-autocomplete can improve performance by reducing redundant API calls

I have successfully implemented a mat-autocomplete feature. However, I am facing an issue where the Http call is triggered with every keyup event, such as 'r', 'ra', 'ram', 'rame', 'ramesh'. This frequent u ...

Design a data structure that encompasses the combined output of multiple functions

I have a set of functions and I want to combine the return types of these functions into a union type. Example Input function types: type InputType1 = () => {type: "INCREASE"} type InputType2 = () => {type: "ADD", by: number} Ou ...

Contrasting createMuiTheme and getMuiTheme

When would you choose to use one over the other? What are the key differences in how they operate? ...

Inserting an HTML element into Handlebars.js during a specific iteration of an each loop

I have a channel.json file containing 7 objects of data which are iterated in hb. I am looking for a way to insert a date between these iterations without modifying the .json file. How can I add an html tag to display after the 3rd iteration within the loo ...

Which is the preferable option for creating a circular daily planner: canvas or SVG?

As a novice programmer delving into the world of coding (or at least hoping to), I have a question regarding graphic tools in html5 for my latest project. My goal is to create a planner app using electron, with the unique twist that the planner form sho ...

Creating packages for multiple Typescript projects that rely on a shared local module

I am currently developing a series of VSTS extensions, with each extension being its own independent Node project complete with its own package.json file and node_modules folder. The structure of the folders is as follows: - MyExtension - package.json ...

Creating an Array in AngularJS with ng-model and submitting it with jQuery: A comprehensive guide

I am struggling to submit an array of values using jQuery and AngularJS. Whenever I click the submit button, only the first array value is being retrieved. How can I get all array values using ng-model? Here is a link to all my code: https://jsfiddle.net/r ...