5

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"]

2 Answers 2

8

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);
   

Sign up to request clarification or add additional context in comments.

1 Comment

"returns an array of properties, which you select" is not very accurate, it doesn't return an array of properties, it returns an array where each item has been mapped into any value you desire by returning it from the callback function.
7

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.