javascript Typescript 按数组过滤对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48401341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:00:33  来源:igfitidea点击:

Typescript filter array of objects by an array

javascript

提问by anand

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

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

采纳答案by Wyns

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

如果您想通过 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 example: https://jsfiddle.net/7xnybhLv/1/

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

回答by pwolaq

In your code you are comparing GroupIdwith an array. You should check if array contains GroupIdinstead.

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

Here is how to do it:

这是如何做到的:

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

For better support you can replace Array.prototype.includeswith Array.prototype.indexOf:

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

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

回答by Aravind

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

回答by Nina Scholz

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

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