Typescript通过数组过滤对象数组

ana*_*and 3 javascript

我必须过滤对象数组以基于另一个数组获取某些值,并且

数据

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]
Run Code Online (Sandbox Code Playgroud)

我的密码

var data = this.inventory .filter(x => x.GroupId == this.value );
Run Code Online (Sandbox Code Playgroud)

无法获取过滤的数据,但返回空数组。提前致谢

Wyn*_*yns 6

如果您想通过 id 字段进行区分,这里有一个解决方案:

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);
Run Code Online (Sandbox Code Playgroud)

JSFiddle 示例:https ://jsfiddle.net/7xnybhLv/1/


pwo*_*laq 5

在您的代码中,您正在GroupId与数组进行比较。您应该检查数组是否包含GroupId

这是操作方法:

var data = this.inventory.filter(x => value.includes(x.GroupId));
Run Code Online (Sandbox Code Playgroud)

为了获得更好的支持,您可以将Array.prototype.includes替换为Array.prototype.indexOf

var data = this.inventory.filter(x => value.indexOf(x.GroupId) !== -1);
Run Code Online (Sandbox Code Playgroud)


Ara*_*ind 5

你应该使用包含

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)));
Run Code Online (Sandbox Code Playgroud)