Typescript按数组过滤对象数组

时间:2018-01-23 12:06:32

标签: 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]

我的代码

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

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

4 个答案:

答案 0 :(得分:5)

在您的代码中,您将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);

答案 1 :(得分:3)

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

答案 2 :(得分:1)

您应该使用包含



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 :(得分:0)

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