在Typescript 2中,如何从对象数组中获取单个属性并分配给新数组?

bri*_*nch 3 javascript arrays typescript typescript2.0 angular

我在TypeScript 2中有这个"模型":

export class MyModel {
   myProperty1: string;
   myProperty2: string;
   ...
}
Run Code Online (Sandbox Code Playgroud)

我也有这门课:

// Leaving out the imports
@Component
...
export class MyClass {
   private myArray: Array<MyModel>;

   ngOnInit() {
      this.myArray = ...// calls a service which returns a populated array of MyModel objects;
   }

   ngAfterViewInit() {
      var newArray: Array<string> = this.myArray ??? // take only myProperty1 from myArray objects and assign to newArray
   }
}
Run Code Online (Sandbox Code Playgroud)

如何只在myArray中使用myProperty1并分配给我的新字符串数组?

因此,如果myArray包含两个MyModel类型的元素:

[{"one", "apple"}, {"two", "oranges"}]
Run Code Online (Sandbox Code Playgroud)

然后newArray应该最终包含这两个string类型的元素:

["one", "two"]
Run Code Online (Sandbox Code Playgroud)

Sur*_*yan 6

使用map()函数.在这种情况下,它获取数组中的每个项目,返回一个属性数组,您可以选择它们.在我的情况下一个数组prop1.

const arrays = [{prop1: "one", prop2: "apple"}, { prop1: "two", prop2: "oranges"}];

const newArr = arrays.map(item => item.prop1);
console.log(newArr);
   
Run Code Online (Sandbox Code Playgroud)


Jua*_*des 5

使用Array.map,它通过处理每个元素创建一个新数组。

this.myArray.map(o => o.myProperty1)
Run Code Online (Sandbox Code Playgroud)