2017-02-15 43 views
2

我有這樣的「模式」,打字稿2:在Typescript 2中,我如何從對象數組中取單個屬性並分配給新數組?

export class MyModel { 
    myProperty1: string; 
    myProperty2: string; 
    ... 
} 

我也有這個類:

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

我怎麼能只拿myProperty1在myArray的,並分配給我的新字符串數組?

所以如果myArray的包含類型爲MyModel的兩個要素:

[{"one", "apple"}, {"two", "oranges"}] 

然後newArray應該結束了包含字符串類型的這兩種元素:

["one", "two"] 

回答

3

使用Array.map,它通過創建新的數組處理每個元素。

this.myArray.map(o => o.myProperty1) 
5

使用map() function.In這種情況下,得到您的陣列中的每個項目,一個收益性的陣列,其中選擇。在我的情況下,一組prop1

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

 
const newArr = arrays.map(item => item.prop1); 
 
console.log(newArr); 
 

+0

「*返回性質的數組,其中選擇*」是不是很準確,它不會返回屬性數組,它返回每個項目已被映射的數組通過從回調函數中返回它想要的任何值。 –

相關問題