使用Typescript按照数组过滤对象数组

10
我需要筛选一个对象数组,根据另一个数组获取特定的值,并且还要去重。

数据

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]

我的代码

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

无法获取经过筛选的数据,但会返回空数组。提前感谢。


inventorythis 作用域中吗?你将其声明为 var inventory,所以它应该只是 inventory.filter(.. - Erik Terwan
显示错误,如“在任何类型中不存在属性'includes'” - anand
这个回答解决了你的问题吗?如何在对象键值在数组中时过滤数组 - Heretic Monkey
4个回答

8

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

以下是如何实现:

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

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

var data = this.inventory.filter(x => value.indexOf(x.GroupId) !== -1);

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

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

显示错误,如“在任何类型中不存在属性'includes'” - anand
使用indexOf代替includes。我更新了答案。 - Wyns
这个方法虽然可行,但我想要更好的解释为什么它可行。例如,为什么我需要 > -1?为什么我需要包括 .findIndex 以及之后的所有内容,我不是认为这就是 filter 的作用吗?> -1 很重要,没有它,代码会导致一个重复的 inventory 数组,但为什么呢?! - Rin and Len
1
@RinandLen:我重构了示例代码并添加了代码注释。希望这能帮助你更好地理解正在发生的事情:https://jsfiddle.net/vrbnoqd9/ - Wyns

5

你应该使用 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)));


2
您可以直接使用变量并使用 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; }


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接