打字稿按数组过滤对象数组

新手上路,请多包涵

我必须过滤一个对象数组以根据另一个数组获取某些值并且也不同

数据

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

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

原文由 anand 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 348
2 个回答

如果你想通过 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/

原文由 Wyns 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

这是如何做到的:

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

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

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

原文由 pwolaq 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏