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 sets $vm.user apart from $vm.$data.user in Vuejs?

When you need to retrieve component data, there are two ways to do so: $vm.user and $vm.$data.user. Both methods achieve the same result in terms of setting and retrieving data. However, the question arises as to why there are two separate ways to access ...

Using TypeScript with AWS Lambda: To package imports or not to package? Alternatively: Error in Runtime.ImportModule: Module '@aws-sdk/...' not found

I have been working with the code in my lambda.ts file, attempting to execute it on an AWS Lambda: import 'aws-sdk' import { /* bunch of stuff... */ } from "@aws-sdk/client-cloudwatch-logs"; import {Context, APIGatewayProxyResult} from ...

Is it possible for me to develop a mobile application using JavaScript, HTML, and CSS and distribute it for sale on the App Store, Google Play Store, and Microsoft Mobile App Store at

I have a keen interest in web standards such as Javascript, HTML, and CSS. My goal is to utilize these languages to develop applications for mobile devices like phones and tablets. I am also considering selling these applications on various platforms inclu ...

eliminating reliance on promises

I understand the importance of promises, however I am faced with a challenge as I have multiple old functions that currently operate synchronously: function getSomething() { return someExternalLibrary.functionReturnsAValue() } console.log(getSomething( ...

Transforming nested arrays using Nifi Jolt to create an array containing custom objects

Struggling to convert nested arrays from JSON input into an array of objects with correct keys and values using Nifi Jolt Transform. The challenge I'm facing is the need to manually specify the column names since they are not evident from the JSON re ...

What is more costly in terms of performance: toggling the visibility of a DOM node or adding/removing a DOM node?

When it comes to calling, which is the more costly operation? Displaying and hiding a DOM node Creating and deleting DOM nodes Let's assume we only have one or a few (less than 5) nodes that require manipulation, and the application is running on a ...

Every time you try to import a config.json file in Typescript, it never fails

I have the most recent version of Visual Studio Code installed. Visual Studio Code is currently utilizing TypeScript v3.3.3. I've successfully installed the following packages via npm, both locally (save-dev) and globally: TestCafe v1.1.0 Core-JS v ...

Having difficulties with long JSON strings? jQuery's JSON.parse might not be the solution for you

As I work on my phonegap app, I encounter an issue with parsing a large JSON string downloaded from a server. Initially, downloading and reading the text data works well using FileReader, but when it comes to parsing the JSON, problems arise. For instance ...

The Jquery calculation is giving unexpected results by returning NaN instead of an integer

Hello, I'm attempting to create a calculation that will add up the values from multiple text inputs and then display the total in another text input field. Below is the code that I have put together for this purpose. However, when I test it out, I see ...

Updating the value of each preceding sibling of every checked checkbox using jQuery upon form submission

After extensive research, I discovered that the most effective approach involves using a clever workaround to capture every tick and untick on a dynamic input row with multiple checkbox arrays. However, none of the solutions provided a viable method. I th ...

Error: [$controller:ctrlreg] - The controller registration has failed

I am currently exploring the world of AngularJs and attempting to display options from a json file. However, I keep encountering the following error message: "Error: [$controller:ctrlreg]" Below is the code snippet I am working with: var sj = angular. ...

What is the maximum number of elements that can be accommodated in an array with a capacity of 5

In C/C++, if I define an array like int arr[5]; and populate it using a loop as shown below: for(int i=0; i<5; i++){ arr[i] = i+1; } When I print the elements with another loop like this: for(int i=0; i<5; i++){ printf("%d ", arr[i ...

Accessing external content within our webpage

Previously, I utilized iframes to display an external page within our asp.net page. However, I have now decided to explore alternative methods that do not involve iframes. My goal is to open an external page within our page using only a simple aspx page wi ...

Angular Automatically Generated Identifier for Event Detection

By using jQuery, I can easily target an ID that starts with "conditionValue" $(document).on('focus', "[id^=conditionValue]", function (event) { // code }); But how can I achieve the same in Angular when looking for an ID starting with somet ...

Ways to cancel a subscription once a specific parameter or value is met following a service/store interaction

I am working with a service that provides a changing object over time. I need to unsubscribe from this service once the object contains a specific property or later when the property reaches a certain value. In situations like these, I typically rely on t ...

When setting up an SQS Event on an S3 Bucket using CloudFormation, the notification destination service region must match the bucket's location constraint to be valid

As I work on creating a cloudformation template that will generate a private bucket and then set up event notification to send a message to a queue whenever an object is created in the bucket, I encounter the following error when running the stack: The no ...

AngularJS Expandable Table - Unlocking Limitless Possibilities

Take a look at the code snippet below: <tbody> <tr ng-repeat-start="ticket in tickets"> <td> <button ng-if="ticket.expanded" ng-click="ticket.expanded = false">-</button> <button ng-if="!t ...

Sorting customization within a complex nested array structure

Sorting a nested array can sometimes be tricky. Consider a JSON structure like the one shown below: var orders = [{ 'orderId': 1, 'sales': [{ 'salesNumbers': 3 }] }, { 'orderId': 2, ...

Error: Unable to cast object of type com.sun.org.apache.xerces.internal.dom.ElementNSImpl to

I am facing a ClassCastException issue and trying to figure out what mistake I might be making here. Attempting (RegistrationRequest)(element.getValue()) doesn't seem to be working as expected. However, I understand that (RegistrationRequest)element.g ...

Error message on Android Web Console: ReferenceError - Worker object is not defined

As someone who is new to javascript, I have been struggling to understand why popular browsers seem to handle the definition "new Worker("BarcodeWorker.js")" differently than Android WebView. The original code for this Barcode Reader is from Eddie Larsso ...