2017-02-15 4 views
2

나는 타이프 2이 "모델"을 가지고 : 나는에서 myArray에서 단지 myProperty1을 가지고 나의 새로운 문자열 배열에 할당 할 수있는 방법Typescript 2에서 개체 배열에서 단일 속성을 가져 와서 새 배열에 할당하는 방법은 무엇입니까?

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

:

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

나는 또한이 클래스가?

그래서에서 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

는 각 항목이 매핑 된 배열을 반환, 그것은 특성의 배열을 반환하지 않는, 아니 매우 정확 "*는 * 당신이 선택 속성의 배열을 반환합니다" 콜백 함수에서 반환하여 원하는 모든 값으로. –