• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

134
Views
How do I transform array into an object with index signature and class as a type?

I have type A, type B and a class called Person. I need to transform array of type A into array of types B and then somehow send it to the class as an input data. I am really stuck and not sure how I do all of this.

Type A and 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}

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.`
    );
}}

I did this:

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

But now I can't call method of class like this for some reason:

for (let person of b) {
         console.log(person.tellUsAboutYourself());
     }
almost 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Consider this example:

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)
}))

Playground

You just need to preserve order of Params elems in Person constructor arguments.

almost 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error