Creating a Map in TypeScript from an Array

I have a series of TypeScript objects structured like this:

interface MyObject {
  id: string,
  position: number
}

My goal is to transform this array into a map format where it shows the relationship between id and position, as needed for a future JSON POST request:

{ 
   "id1": 1,
   "id2": 2,
}

One option is utilizing an ES6 Map:

array.reduce((map, obj) => map.set(obj.id, obj.position), new Map())

This method works well, but converting an ES6 Map to JSON can be tricky.

I've attempted to convert the key-value pairs into a plain object using various strategies such as Indexable Types, Object.create({}), and other approaches, but TypeScript doesn't seem to agree with any of my attempts.

How can I efficiently extract a pure object literal containing key-value pairs from an array of objects?

Answer №1

If your target environment has support for ES2019, you have the option to utilize Object.fromEntries(), as shown below:

function arrToObjES2019(arr: MyObject[]) {
  return Object.fromEntries(arr.map(({ id, position }) => [id, position]));
}

Alternatively, if not supported, you can create a custom polyfill-like version of Object.fromEntries() using array reduce() on an empty object, like this:

function fromEntries<V>(iterable: Iterable<[string, V]>) {
  return [...iterable].reduce((obj, [key, val]) => {
    obj[key] = val
    return obj
  }, {} as {[k: string]: V})
}

and then apply it as follows:

function arrToObj(arr: MyObject[]) {
  return fromEntries(arr.map(({ id, position }) => [id, position]));
}

Both methods should allow you to achieve your desired outcome:

const arr: MyObject[] = [
  { id: "id1", position: 1 },
  { id: "id2", position: 2 }
];

console.log(JSON.stringify(arrToObj(arr))); // {"id1":1,"id2":2}

Hope that was helpful. Best of luck!

Link to code

Answer №2

If you're looking for an easy solution, try the following approach:

Create a new map by mapping through the array and setting key-value pairs using obj.id and obj.position.

Answer №3

It seems to me that using reduce would be the best solution in this scenario...

const transformedArray = array.reduce((accumulator, value) => 
   Object.assign(accumulator, {[value.id]: value.position}), {});

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

What is the best approach to make changes to a 2D array within a React component?

I'm working on saving a list of equipment in arrays, and I need to assign a quantity to each piece of equipment. To do this, I want to transform my one-dimensional array into a two-dimensional array. How can I declare a 2D array in the state? this.s ...

Is it possible to dynamically add the URL to an iframe based on a condition being true, and then iterate through a list of URLs before

I'm trying to figure out how to change the URL in an iframe based on the presence of a class="show". The first time the element has the class "show," it should load about.html. The second time the same element has the class "show," it should open wor ...

Having issues with Gson resetting values for fields that are missing in the JSON response. Any suggestions for fixes or workarounds?

An issue seems to have been filed here: https://github.com/google/gson/issues/513 I am facing a problem with Gson that I cannot seem to resolve as I am relatively new to it. In my Plain Old Java Object (POJO), there is a boolean field that I manually set ...

The RxJS observable fails to initiate the subscribe function following the mergeMap operation

I am attempting to organize my dataset in my Angular application using the RxJS operators and split it into multiple streams. However, I am facing difficulties making this work properly. Inside my SignalRService, I have set up a SignalR trigger in the cons ...

A difference in the way content is displayed on Firefox compared to Chrome, Edge, and Safari

Recently, I encountered an issue with a tool I had developed for generating printable images for Cross-Stitch work. The tool was originally designed to work on Firefox but is now only functioning properly on that browser. The problem at hand is whether th ...

The issue arises with loading data from the server due to lack of definition of Mongo

I am experiencing a console bug and need assistance. It seems that there is an issue with loading data from the server as I am getting an error stating "Mongo is not defined." C:\Users\Robert\Desktop\FINISH\node_modules\mongod ...

I'm trying to create a drop-down list in JS that will save selected options to a database using PHP. I'm feeling a bit lost, anyone

My goal is to upload a pdf file with specific options that determine its category. The challenge arises when creating multiple options, as the second option depends on the first choice and involves JavaScript functionality for which I am unsure how to stor ...

utilizing angularjs and bootstrap to manage multiple button models

Recently delved into learning angularjs and bootstrap. Found a tutorial on creating buttons. <div ng-controller="ButtonsCtrl"> <h4>Checkbox</h4> <pre>{{checkModel}}</pre> <div> <button type="butto ...

Jumping over loop iteration following a JavaScript catch block

Currently, I am developing an API that requires making repeated calls to another API (specifically, Quickbooks Online) within a loop. These calls are encapsulated in promises that either resolve or reject based on the response from Quickbooks. Everything f ...

Invoke a functional component when a button is clicked in a React application

I have a functional component that includes a button. My goal is to trigger another functional component when this button is clicked. Upon clicking the Submit button, the Preview button appears. When the user clicks on the preview button, it should call t ...

Hiding a Div Using jQuery Depending on User's Choice

Currently, I am in the process of developing an employee directory using AJAX/jQuery with the assistance of the Random User Employee Directory API. You can access the data feed that I am utilizing by following this link: I have successfully created a webp ...

Scrolling to a specific element using jQuery after a specified delay has

On my website, I have a page with an autoplaying video located at . My goal is to implement a feature where once the video completes playing after a specific duration, the webpage will automatically scroll down to the text section. This scroll action sho ...

Is there a way to retrieve the io object within the io.sockets.on callback function?

My preference is to not alter my sockets method. I was hoping to be able to utilize the io object within the connected function. Could this be a possibility? function sockets (server) { const io = require('socket.io')(server); io.sockets.on ...

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

Developing a Rails application integrated with Pusher or Faye for real

I've been tasked with creating an app similar to this: I'm facing challenges in updating the bids. I am considering using technologies like Pusher or Faye ( or ) and subscribing to each event. However, I'm wondering if there is a more elega ...

Within an Angular test scenario, execute a static method from a service that triggers an HTTP get request to fetch stored JSON data. This data is then retrieved and returned back to the service

Currently, I am facing a challenge in my Angular test case where I am trying to load JSON data via an HTTP call. The issue arises when a static method is called from a service spec file named "url-service.spec" to another service named "load-json.service. ...

Issue: [Issue: ENOENT: the file or directory './1695556319341.mp3' does not exist]

I am currently facing an issue while trying to convert an mp4 file to an mp3 file and then uploading it directly to Firebase storage without saving it locally on my machine. The error I encounter is "Error: [Error: ENOENT: no such file or directory, open ...

Uncover the contents of a JSON array by employing generics and leveraging the power of

I'm currently working on an app to gain a better understanding of using generics in Swift. To achieve this, I decided to utilize Studio Ghibli's API Here's my approach: Send a request to the API Receive the response Parse the JSON data T ...

Dynamically parallelizing functions with async and arrays

I have recently integrated the fantastic "async" module by caolan into my Node.js project: Below is a snippet of the code in question: exports.manageComments = function(req, res) { var toDeleteIds = []; var deleteFunctions = []; if (req.body. ...

The error "TypeError: ollama.chat is not a function" has occurred when trying to use the ollama module in

Currently, I am grappling with a Node.js project that requires me to utilize the ollama module (ollama-js). The problem arises when I invoke the async function chatWithLlama() which contains ollama.chat(), resulting in the following error being thrown: Ty ...