简体   繁体   中英

efficient way to get values from object based on id list

I have list of users :

users: Array<any> = [{id:1,name:'A'},{id:2,name:'B'},{id:3,name:'C'}];

and

this.selectedUsers = [1,2];

How do I get all the objects from the users array having an id found in the selectUsers array?

您可以将indexOf与filter一起使用。

this.users.filter(user => this.selectedUsers.indexOf(user.id ) > -1)

I think this should do what you want:

var found = this.users.filter(
    item => this.selectedUsers.some(id => item.id == id)
)

update

var found = this.users.filter(
    item => this.selectedUsers.some(id => item.id == id)
).forEach(item => {
  item.label = item.name;
  item.name = undefined;
});

or

var found = this.users.filter(
    item => this.selectedUsers.some(id => item.id == id)
).map(item => {id: item.id, label: item.name});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM