![](/img/trans.png)
[英]How do I take an array of objects from state and push a specific value of the objects into a new array
[英]In Typescript 2 how can I take single property from array of objects and assign to new array?
我在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
}
}
如何只在myArray中使用myProperty1並分配給我的新字符串數組?
因此,如果myArray包含兩個MyModel類型的元素:
[{"one", "apple"}, {"two", "oranges"}]
然后newArray應該最終包含這兩個string類型的元素:
["one", "two"]
使用map()函數。在這種情況下,它獲取數組中的每個項目,返回一個屬性數組,您可以選擇它們。 在我的例子中, prop1
數組。
const arrays = [{prop1: "one", prop2: "apple"}, { prop1: "two", prop2: "oranges"}]; const newArr = arrays.map(item => item.prop1); console.log(newArr);
使用Array.map ,它通過處理每個元素來創建一個新數組。
this.myArray.map(o => o.myProperty1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.