I have this "model" in TypeScript 2:
export class MyModel {
myProperty1: string;
myProperty2: string;
...
}
I also have this 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
}
}
How can I take only the myProperty1 in myArray and assign to my new string array?
So if myArray contains two elements of type MyModel:
[{"one", "apple"}, {"two", "oranges"}]
Then newArray should end up containing these two elements of type string:
["one", "two"]
Use map() function.In this case it gets each item in your array, an returns an array of properties, which you select. In my case an array of prop1
.
const arrays = [{prop1: "one", prop2: "apple"}, { prop1: "two", prop2: "oranges"}];
const newArr = arrays.map(item => item.prop1);
console.log(newArr);
Use Array.map, it creates a new array by processing each element.
this.myArray.map(o => o.myProperty1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With