在typescript中更改数组的类型

问题描述 投票:0回答:3

我有这种类型的数组:

0: Client
clientId: 405229
clientName: "Test, Jamie"
1: Client
clientId: 405288
clientName: "Test1, Jamie"
2: Client
clientId: 405239
clientName: "Test3, Jamie"

我基本上想把它转换成一个没有类的普通数组

0:
clientId: 405229
clientName: "Test, Jamie"
1:
clientId: 405288
clientName: "Test1, Jamie"
2: 
clientId: 405239
clientName: "Test3, Jamie"

我试过做:

Array.map(x=> new Array(x))

但是会产生相同的结果。

任何帮助?

javascript arrays typescript
3个回答
1
投票

这是一个很好的功能性ES6-ish方式:

    // Make the typed array
    const clients : Array<Client> = [];
    for ( let i = 0; i < 10; i++ ) {
      clients.push ( new Client ( i, 'client_' + i.toString () ) );
    }

    // This is the magic line, just spread the object
    const plain = clients.map ( x => ( { ...x } ) );

    // First logs as a typed array, 
    // second as just plain old objects
    console.log ( clients );
    console.log ( plain );

Trace of arrays


1
投票

如果你想使它适用于任何对象,我会使用javascript Object.keys,它将返回所有对象自己的属性名称,阅读更多关于它的信息here

然后创建一个将映射任何类对象的函数。

let clientArray : Client[] = [ 
  new Client(24, 'Kobe'), 
  new Client(23, 'Lebron James'),
  new Client(1, 'Zion Williams')
]
let productsArray : Product[] = [ 
  new Product(24, 'Sneakers'), 
  new Product(23, 'Bling),
]

// use this function to map any class to to a simple object.
function mapToSimple(client){ 
    let keys = Object.keys(client)
    let result = {}
    keys.forEach((key) => {
        result[key] = client[key];
    })
    return result;
};

let results = clientArray.map(mapToSimple)
let anotherResults = productsArray.map(mapToSimple)
console.log(results);
console.log(anotherResults);

0
投票

Clients数组映射到Client属性数组需要提供map函数的函数来挑选属性。例如

说有以下Client类:

class Client {
   clientId: Number;
   clientName: string;

   constructor(clientId: Number, clientName: string) {
      this.clientId = clientId;
      this.clientName = clientName;
   }
}

并且有一个初始的Client实例数组。

const clientInstances  : Client[] = [ 
  new Client(1, 'Raymond'), 
  new Client(2, 'Damond') 
]

console.log(clientInstances);
// [ Client { clientId: 1, clientName: 'Raymond' },
//   Client { clientId: 2, clientName: 'Damond' } ]

提供给map方法的函数将传递给每个客户端实例,并返回一个新对象,该对象具有为相关键设置的客户端属性值。

interface IClient { 
    clientName: string;
    clientId: Number; 
}

const clientObjects : IClient[] = clientInstances.map(
  client => (
    { clientName: client.clientName, clientId: client.clientId }
  )
)

console.log(clientObjects);
// [ { clientName: 'Raymond', clientId: '1' },
//   { clientName: 'Damond', clientId: '2' } ]
© www.soinside.com 2019 - 2024. All rights reserved.