kiranghule27
kiranghule27

Reputation: 443

Typescript filter method

In my angular 2 application I have declared 2 object arrays.

users: User[];
selectedUsers: User[];

Now I am using the filter() method to return an array with objects whose checked property is true.

this.selectedUsers = this.users.filter(user => user.isChecked == true);

The problem is the references for elements of both arrays are same. So is there a way to that I can filter out objects and return array of new objects(new reference)?

Upvotes: 2

Views: 11109

Answers (3)

Amid
Amid

Reputation: 22352

Lets take @Amir answer and make it a tiny bit more typescript friendly:

this.users.filter(user => user.isChecked).map(u => {...u});

Upvotes: 2

YairTawil
YairTawil

Reputation: 4101

You can use _.cloneDeep function ("lodash" library):

for implement lodash in typescript you need:

npm i -S lodash

and the @types lib :

npm i -S @types/lodash

and in your code:

import * as _ from 'lodash'

let cloneCheckedObject = _.cloneDeep(this.users.filter(user => user.isChecked);

Upvotes: 5

Amir Popovich
Amir Popovich

Reputation: 29836

You can always use Array.prototype.map to create a new array and Object.assign to create a new object:

this.users.filter(user => user.isChecked).map(u => Object.assign({},u));

Upvotes: 9

Related Questions