class Test{
constructor(private Name: string, private Id: number, private isAlive: boolean){}
array1?: string[];
}
想象一下 数组使用API响应中的一堆数据初始化。我有一组测试对象。我现在需要的是将该数组中所有这些对象的名称提取到一个新数组中。 我找不到用于此问题的打字稿语法。
答案 0 :(得分:0)
我现在需要的是将该数组中所有这些对象的名称提取到一个新数组中
使用Array.prototype.map
:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
从Name[]
中,您想要string[]
:
const array1: string[] = names.map(x=>x.fieldThatIsTheStringYouWant);
答案 1 :(得分:0)
Typescript(或多或少)是javascript的超集。同样的Javascript解决方案也适用于Typescript。
const output = input.map( item => item.name );
答案 2 :(得分:0)
var originalObject = [
{"first":"Gretchen","last":"Kuphal","email":"greenwolf54@gmail.com","address":"416
Lesch Road","created":"March 1, 2012","balance":"$9,782.26"}];
1。您只想复制数组
var duplicateObject = originalObject;
duplicateObject[0].first
alert(duplicateObject[0].first);
Editrd 这也可以做到
var originalObject = [
{"first":"Gretchen","last":"Kuphal","email":"greenwolf54@gmail.com","address":"416 Lesch Road","created":"March 1, 2012","balance":"$9,782.26"},
{"first":"Morton","last":"Mayer","email":"salmonsquirrel25@gmail.com","address":"1602 Bernhard Parkway","created":"April 29, 2017","balance":"$6,596.11"},
{"first":"Catalina","last":"Daugherty","email":"Catalina.Daugherty@filomena.name","address":"11893 Kali Vista","created":"October 16, 2008","balance":"$6,372.86"},
{"first":"Orpha","last":"Heaney","email":"turquoisewolf22@gmail.com","address":"8090 Chris Stream","created":"November 21, 2015","balance":"$9,596.26"},
{"first":"Reva","last":"Mohr","email":"Reva.Mohr@oda.net","address":"0291 Kailyn Stravenue","created":"November 6, 2014","balance":"$4,768.37"},
{"first":"Loma","last":"Keeling","email":"turquoisegiraffe09@gmail.com","address":"84460 Samson Knoll","created":"June 13, 2017","balance":"$9,361.16"}
];
var duplicateObject=new Array();
for (let num of originalObject) {
duplicateObject.push(num.first);
}
// print
for (let first of duplicateObject) {
console.log(first);
}