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

0

138
Views
¿Cómo transformo una matriz en un objeto con firma de índice y clase como tipo?

Tengo tipo A, tipo B y una clase llamada Persona. Necesito transformar la matriz de tipo A en una matriz de tipos B y luego enviarla de alguna manera a la clase como datos de entrada. Estoy realmente atascado y no estoy seguro de cómo hago todo esto.

Tipo A y matriz de este tipo:

 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']];

Tipo B:

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

Persona de clase:

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

Hice esto:

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

Pero ahora no puedo llamar a un método de clase como este por alguna razón:

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

0

Considere este ejemplo:

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

Patio de juegos

Solo necesita conservar el orden de los elementos Params en los argumentos del constructor Person .

over 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

Show me some job opportunities
There's an error!