Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Typescript 2 how can I take single property from array of objects and assign to new array?

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"]
like image 625
brinch Avatar asked Dec 19 '22 09:12

brinch


2 Answers

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);
   
like image 178
Suren Srapyan Avatar answered Dec 20 '22 23:12

Suren Srapyan


Use Array.map, it creates a new array by processing each element.

this.myArray.map(o => o.myProperty1)
like image 27
Juan Mendes Avatar answered Dec 20 '22 21:12

Juan Mendes