在 Typescript 2 中,如何从对象数组中获取单个 属性 并分配给新数组?
In Typescript 2 how can I take single property from array of objects and assign to new array?
我在 TypeScript 2 中有这个 "model":
export class MyModel {
myProperty1: string;
myProperty2: string;
...
}
我也有这个class:
// 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
}
}
如何只获取 myArray 中的 myProperty1 并分配给我的新字符串数组?
因此,如果 myArray 包含两个 MyModel 类型的元素:
[{"one", "apple"}, {"two", "oranges"}]
那么 newArray 最终应该包含这两个字符串类型的元素:
["one", "two"]
使用Array.map,它通过处理每个元素创建一个新数组。
this.myArray.map(o => o.myProperty1)
使用 map() function.In 在这种情况下,它获取数组中的每个项目,一个 returns 属性数组,您 select。在我的例子中,数组 prop1
.
const arrays = [{prop1: "one", prop2: "apple"}, { prop1: "two", prop2: "oranges"}];
const newArr = arrays.map(item => item.prop1);
console.log(newArr);
我在 TypeScript 2 中有这个 "model":
export class MyModel {
myProperty1: string;
myProperty2: string;
...
}
我也有这个class:
// 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
}
}
如何只获取 myArray 中的 myProperty1 并分配给我的新字符串数组?
因此,如果 myArray 包含两个 MyModel 类型的元素:
[{"one", "apple"}, {"two", "oranges"}]
那么 newArray 最终应该包含这两个字符串类型的元素:
["one", "two"]
使用Array.map,它通过处理每个元素创建一个新数组。
this.myArray.map(o => o.myProperty1)
使用 map() function.In 在这种情况下,它获取数组中的每个项目,一个 returns 属性数组,您 select。在我的例子中,数组 prop1
.
const arrays = [{prop1: "one", prop2: "apple"}, { prop1: "two", prop2: "oranges"}];
const newArr = arrays.map(item => item.prop1);
console.log(newArr);