Typescript filter array of objects by an array

2020-06-04 03:39发布

I have to filter an array of objects to get certain values based on an another array and distinct also

Data

var value:any[]

 var inventory = [
        {id: 1, quantity: 2, GroupId: 1},
        {id: 2, quantity: 0, GroupId: 2},
        {id: 1, quantity: 2, GroupId: 1}
    ];

   //data from db
   value = [1,2]

My code

var data = this.inventory .filter(x => x.GroupId == this.value );

Not able to get the filtered data, but returning empty array. Thanks in advance

标签: javascript
4条回答
Lonely孤独者°
2楼-- · 2020-06-04 03:54

You should be using includes

console.log([
        {id: 1, quantity: 2, GroupId: 1},
        {id: 2, quantity: 0, GroupId: 2},
        {id: 3, quantity: 2, GroupId: 1}
    ].filter(x => [1,2].includes(x.id)));

查看更多
萌系小妹纸
3楼-- · 2020-06-04 03:55

If you want to distinct by the id field here's a solution:

var inventory = [
        {id: 1, quantity: 2, GroupId: 1},
        {id: 2, quantity: 0, GroupId: 2},
        {id: 1, quantity: 2, GroupId: 1}
    ];

var value = [1,2]
var data = inventory.filter(x => value.indexOf(x.GroupId)>-1).filter((elem1, pos, arr) => arr.findIndex((elem2)=>elem2.id === elem1.id) === pos);
console.log(data);

JSFiddle example: https://jsfiddle.net/7xnybhLv/1/

查看更多
▲ chillily
4楼-- · 2020-06-04 03:59

You could use the variable directly and use Array#includes.

var inventory = [{ id: 1, quantity: 2, GroupId: 1 }, { id: 2, quantity: 0, GroupId: 2 }, { id: 3, quantity: 2, GroupId: 1 }],
    value = [1, 2],
    data = inventory.filter(({ GroupId }) => value.includes(GroupId));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

查看更多
在下西门庆
5楼-- · 2020-06-04 04:18

In your code you are comparing GroupId with an array. You should check if array contains GroupId instead.

Here is how to do it:

var data = this.inventory.filter(x => value.includes(x.GroupId));

For better support you can replace Array.prototype.includes with Array.prototype.indexOf:

var data = this.inventory.filter(x => value.indexOf(x.GroupId) !== -1);
查看更多
登录 后发表回答