What is the most effective way to convert an array into an object using index signatures and classes as types?

I am facing a challenge involving transforming an array of type A into an array of type B and then passing it to a class called Person as input data. I am currently stuck and uncertain about how to accomplish this task.

Here is the definition of Type A and an array of this type:

type A = Array<[string, number, string]>;
const a: A = [
['Name1', 15, 'City1'],
['Name2', 44, 'City2'],
['Name3', 23, 'City3'],
['Name4', 73, 'City4'],
['Name5', 12, 'City5'],
['Name6', 37, 'City6']];

Type B:

type B = {
[id: string]: Person}

Definition of Class Person:

class Person {
_id: string; // must be unique
age: number;
name: string;
city: string;

constructor(data) {
    if (data == null) {
        console.log("No data presented")
    } else {
        this._id = data._id
        this.age = data.age
        this.name = data.name
        this.city = data.city
    }
}

tellUsAboutYourself() {
    console.log(
        `Person with unique id = ${this._id} says:\n 
         Hello! My name is ${this.name}. I was born in ${this.city}, ${this.age} years ago.`
    );
}}

This is my attempt at solving the problem:

export const b: B[] = a.map(([name, age, city], index) => ({
[index]: new Person({ _id: index, name, age, city })}))

However, I am unable to call methods of the class using the following code:

for (let person of b) {
         console.log(person.tellUsAboutYourself());
     }

Answer №1

Take a look at this scenario:

type Params = [name: string, age: number, city: string]

type A = Array<Params>;

type B = {
  [id: string]: Person
}

class Person {
  constructor(
    public _id: string,
    public name: string,
    public age: number,
    public city: string
  ) { }

}

const a: A = [
  ['Name1', 15, 'City1'],
  ['Name2', 44, 'City2'],
  ['Name3', 23, 'City3'],
  ['Name4', 73, 'City4'],
  ['Name5', 12, 'City5'],
  ['Name6', 37, 'City6']
];



export const b: B[] = a.map((elem, index) => ({
  [index]: new Person(`${index}`, ...elem)
}))

Try it out

Ensure the order of Params elements is retained in the Person constructor arguments.

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

Issue with incorrect date being retrieved in MongoDB response from a node server

My date in mongodb is structured as follows: ISODate("2020-08-03T00:00:00.000+05:30"), However, after querying the date, it appears like this: 2020-08-02T18:30:00.000Z I am looking to get the correct date of 2020-08-03. What could I be doing wr ...

What to do when encountering a problem with HTML, CSS, and JS while loading a webpage from an SD card to a WebView

I am facing an issue while loading an HTML file from the SD card to a webview. The problem is that the CSS, images, and videos are not loading properly in the webview. Compatible with Android 4.4 KitKat and Chrome version Not compatible with versions belo ...

What is the best way to transfer the elements of an array with unequal lengths to another array?

I've encountered a straightforward issue that I'm attempting to tackle with the following code snippet: import random n=399 x=np.random.randn(n,n) m=400 y=np.zeros((m,m)) I need to transfer the elements from array x to array y at specific positi ...

Can you identify the issue with this particular JSON parsing function's reviver?

I am trying to parse a JSON string with a reviver function to only include specific properties. Here is my code snippet: const whitelist = ['prop1', 'prop2', 'result']; const reviver = (key, value) => { if (whitelist.i ...

define a function with default arguments and a callback

When working with a JavaScript library, I encountered an issue where I needed to define my callback functions within an object. The goal was to include default parameters in the arguments of these callback functions stored in a TypeScript object. Here is a ...

The requested file at http://localhost:7575/index.js could not be found and was aborted with a 404 error

https://i.sstatic.net/ww9AU.png I have set up endpoints for HTML pages, but I am facing an issue where images and files are not being pulled. Every file path I try results in the error message "GET http://localhost:7575/index.js net::ERR_ABORTED 404 (Not F ...

having trouble connecting to localhost:8081 with node.js

When I accessed the address http://localhost:8081 in my browser after opening server.js, I encountered a message saying "Upgrade Required" at the top left corner of the website. What could be causing this issue? Do I need to upgrade something else? Below ...

What is the best way to manage the loading and unloading of JavaScript within dynamically loaded partial pages?

Utilizing jQuery and history.js, I manage seamless transitions between partial pages to prevent entire document reloads. Some of these partial pages include unique javascript files. Despite successful page transitions, remnants of executed javascript linge ...

Tips for creating a mobile-responsive React + MUI component

A React component utilizing Material-UI (MUI) has been created and I am working on making it mobile responsive. The current appearance is as follows: https://i.stack.imgur.com/8z0T8.png My goal is to have it look like this: https://i.stack.imgur.com/L8g ...

Implementing data updates in Ruby on Rails through AJAX or jQuery

Within a text field input lies the value of a database attribute (ref). Upon focusing on the field, a border appears and disappears upon clicking out. My dilemma is that I wish for the data within the text field to be saved in the database without the nee ...

What is the reason behind typescript making it necessary for me to find a way to set a value of type

function f1() { const v : string = String(); if(v) {alert("IF");} // OK const b : boolean = v; // Type 'string' is not assignable to type 'boolean'. if(b) {alert("BOOLEAN");} } f1(); My approach to this issue involv ...

Configuring Express-JS to route example.com to a specific static file, while directing example.com/anything to a different destination

I am a beginner with Parse and I am currently working on deploying my app to example.com. My goal is for example.com to display a static landing page, while any path like example.com/anything should be handled by a different controller. To illustrate fur ...

Choose particular content enclosed by two strings (across multiple lines)

Looking to use regex to extract specific text between two strings. For example: foo I have four toys bar //single line foo //multiline I have four toys bar foo I have three pets bar foo I have three pets bar How can I extract the text between & ...

Locate a group of DOM selectors that correspond to the highlighted text

Imagine you're at a certain location and you highlight some text: https://i.sstatic.net/8PGvD.png When you inspect the DOM, you see it's represented like this: https://i.sstatic.net/rL0Og.png The actual text is: "Local embassy – For Wikiped ...

Watch for changes in a nested collection in Angular using $scope.$watch

Within my Angular application, there is a checkbox list that is dynamically generated using nested ng-repeat loops. Here is an example of the code: <div ng-repeat="type in boundaryPartners"> <div class="row"> <div class="col-xs- ...

Animating SVG fills based on height using JavaScript

I am looking to create an animated gradient effect using JavaScript instead of CSS. I want the gradient animation to change based on the height in both SVG elements. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="200" height="20 ...

Identify when a mouse hovers within 10 pixels of a div using jQuery

Is it possible to detect when a user hovers over a specific area within a div using JavaScript or jQuery, without adding any additional tags? -------------------------------- -------------------------------- -------------------------------- -------- ...

Determine if an object in TypeScript generics includes a specific value

I have been working on a method to verify if a value retrieved from the database matches an enum. At first, I aimed to create a generic TypeGuard, but then I thought it would be beneficial to have a function that not only checks the value against the enum ...

Manifest JSON not displaying Add to Home Screen prompt

I am trying to implement the prompt for adding to the home screen using manifest.json, but I am facing an issue where the prompt is not showing up even though my PWA score in the audit is 100%. Below is the structure of my dist folder: https://i.sstatic. ...

Adjust the size of the iframe image to fit seamlessly within the design

Is there a way to adjust the size of the image on the right without altering the layout design? The current GIF is 500x500px, but it is only displaying as 100x100px. Any assistance would be greatly appreciated! To see what I currently have (Demo with code ...