Transforming an array into an indexed object using Typescript

I have a specific type of array that I need to convert into an indexed object with corresponding types.

interface IArray {
   id: "message1" | "message2" | "message3";
   message: string;
}

const myArray: IArray[] = [
   {
      id: "message1",
      message: "Here is your message 1"
   },
   {
      id: "message2",
      message: "Here is your message 2"
   }
]

To achieve this, I want to write a function that transforms the array into an object structured like this:

const myObject = {
   message1: "Here is your message 1",
   message2: "Here is your message 2"
}

The challenge I'm facing is that the resultant myObject ends up having the generic type any, but I intend for it to have keys indexed based on the id type defined in the array.

Answer №1

let messages = [{id: "1", text: "This is message 1"},{id: "2", text: "This is message 2"}]
const result = messages.reduce((accumulator, currentValue) => {
  accumulator[currentValue.id] = currentValue.text;
  return accumulator;
}, {});
console.log(result);

Answer №2

To achieve this, you can utilize the forEach method:

JavaScript Example:

let myArray = [{
    id: "message1",
    message: "Here is your message 1"
  },
  {
    id: "message2",
    message: "Here is your message 2"
  }
];
let myObject = {};
myArray.forEach(item => {
  myObject[item.id] = item.message;
});
console.log(myObject);

TypeScript Example:

interface IArray {
  id: "message1" | "message2" | "message3";
  message: string;
}
const myArray: IArray[] = [{
    id: "message1",
    message: "Here is your message 1"
  },
  {
    id: "message2",
    message: "Here is your message 2"
  }
];
let myObject: any = {};
myArray.forEach(item => {
  myObject[item.id] = item.message;
});
console.log(myObject);

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

Attempting to fetch JSON data using jQuery

Trying to retrieve the JSON data using the example from www.w3schools.com. I changed the JSON URL to "http://www.w3schools.com/jquery/demo_ajax_json.js" and saved it in my desktop index.html. However, it does not work on my local machine or when I upload ...

What causes React to update the value of a read-only prop?

For this issue, I created a Codesandbox example. In the My App function, there is an array of objects called webItem. This webItem is passed as a property to the CreateWeb dialog window function. Within the code, I assign the webItem property to a variab ...

Exploring the world of dynamic routing in Angular using JSON data

I am facing an important query. Can we implement async routing in Angular 10? I have come across AsyncRoute in Angular2, but it seems to no longer exist in Angular 10. Here is a snippet of my code : getRoutes() { return this.http.get(this.APIROOT + &a ...

Monitor checkbox status to trigger confirmation dialog

My goal is to prevent the checkbox from changing if 'NO' is clicked in a dialog. The dialog pops up, but I can't figure out how to wait for it to close before allowing the checkbox change. I've attempted using Promises and doing everyt ...

Why does Laravel DatePicker consistently default to showing the previous month instead of the selected month?

I've hit a roadblock trying to pinpoint the source of this error in the Tailwind UI Datepicker. Whenever I choose 09-08-2021 on the visual Datepicker, the value ends up saving as 09-07-2021. I've researched similar cases where the month value re ...

Error: The Vue prop being passed to the component is not recognized

After analyzing the code snippet provided, an error message of "ReferenceError: myvar is not defined" has been observed. Is there a logical issue present in this code? Interestingly, when running it without a jQuery wrapper, the error disappears but the ex ...

How to extract audio array buffer using inputBuffer.getChannelData in HTML5 Audio API

In the process of developing an application, I am working on capturing mic data from the inputBuffer and streaming it to another client for playback. However, I am encountering difficulties in getting this functionality to work properly. Although my recor ...

Combining Two JSON Arrays Featuring Unique Keys

I have two JSON arrays with slightly different keys. The first JSON array contains the keys id, name, and title. The second JSON array includes id, title, forename, name, and company. I am wondering if it's possible to merge these two arrays so th ...

Leveraging a single jquery ajax request to handle various loops

I've been pondering if it's possible to have multiple loops, each with its own Ajax call. My goal is to create a golf scorecard where I can retrieve data for the scorecard and players in a single JSON/Ajax call... This is how I retrieve the scor ...

What is the best way to activate a jQuery function using a dropdown menu?

I have 2 asp:DropdownLists with an OnSelectedIndexChanged attribute. I want to trigger a jquery function when this event occurs to indicate to the user that data processing is taking place. How can I implement this jQuery function without having to use t ...

Transferring data from an array to a view in an Android application

I have successfully retrieved data from a MySQL database and stored it in arrays in my android app using the code below: Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","lo ...

Storing a new field without saving mongoose.Types.ObjectId as a database column in MongoDB

Trying to establish a relationship between two collections in MongoDB. I have a User collection with unique _id for each user, and a News collection where each news item should be linked to a specific user using their userId. In my API workflow, the userI ...

Determine if I'm actively typing in the input field and alter the loader icon accordingly with AngularJS

Just delving into the world of AngularJS and attempting to tweak an icon as I type in an input box. Currently, I can detect when the box is focused using the following code: $scope.loading = false; $scope.focused = function() { console.log("got ...

The .slice() function in TypeScript has the ability to alter the initial array

I am diving into TypeScript and just tackled my first slice() method. My understanding is that the slice() method is supposed to create a copy of an array. Here's a snippet of the code: class ChapterOne { // Gauss Jordan Elimination // No ...

Access both the key and value during iteration with foreach

Currently, I am able to retrieve the value from a PHP object array, but I also need to access the key associated with it. The key is dynamic and cannot be manually defined. foreach($decodedItemMeta->meta as $key => $meta_item){ echo '<li ...

Using Jquery select2 to transfer and fetch information

Hey there, I've been experimenting with the jquery select2-plugin and I wanted to share the basic usage: Here's a simple example: <select style="width:300px" id="source"> <optgroup label="Alaskan/Hawaiian Time Zone"> < ...

Ways to center align text in a div vertically

I'm working with 2 divs that are floating side by side. The left div contains a part number, which is only one line. The right div holds the product description, which can span multiple lines. I am looking for a way to vertically align the text in t ...

Navigating safely with the v-model directive in Vue.js

Let's consider the input component below: <input type="text" v-model="example.modules.report.description.title"></input> See full source I don't want to manually define the object structure in the data: example: { modules: { ...

I am interested in implementing a "slide up" effect for the "slide menu" when it loses focus

When I focus out of the asmenu class, I attempt to trigger a 'slide up' effect. However, if I select two checkboxes from the child elements within the asmenu class, the focusout event is still triggered. Ideally, I would like the 'slide up& ...

What is the process for parsing JSON data using PHP?

I've received the JSON format below and I'm looking to decode it in PHP. However, I'm struggling to figure out how to extract the data within the DATA key in this particular format. JSON: firedAt => Thu, 05 Feb 2015 20:00:13 GMT event ...