如何匹配字符串中的几个单词以过滤数组项 [英] How to match few words from a string to filter array items
问题描述
我有两个数组.一个具有多个字段和 Name
字段,另一个具有仅 Name
字段.我想根据第二个数组 Name
从第一个数组中过滤出数组项.我的第一个数组
I have two arrays. One has multiple fields and Name
field, another one has only Name
field. I want to filter array items from first array based on 2nd array Name
. My first array
{
"Failed": 0,
"Resume": false,
"Name": "GRP.Compiled.Release"
},
{
"Failed": 0,
"Resume": false,
"Name": "GPST.NonPermit.Inacitve"
},
{
"Failed": 0,
"Resume": false,
"Name": "PGVF.NonSubmit.Action"
},
{
"Failed": 0,
"Resume": false,
"Name": "PGVF.NonSubmit.Action"
},
我只有一个带有 Name
字段的数组 Names
,
I have one more array Names
only with Name
field
{
"Name": "NonSubmit"
},
{
"Name": "NonPermit"
},
这是我的代码,无法正常工作
This is my code which is not working
for (let i = 0; i < Names.length; i++)
{
//let obj1=products.filter(x=>Names[i].search(/x.Name/g))
var obj2=products.filter(x=>Names[i].includes(x.Name))
}
我正在寻找下面输出的第一次迭代
The first iteration I am looking for below output
{
"Failed": 0,
"Resume": false,
"Name": "GPST.NonPermit.Inacitve"
},
{
"Failed": 0,
"Resume": false,
"Name": "PGVF.NonSubmit.Action"
},
{
"Failed": 0,
"Resume": false,
"Name": "PGVF.NonSubmit.Action"
},
我该怎么做?
推荐答案
使用 Array.prototype.some
,您可以检查 arr1
项是否包含 arr2
项.
Using Array.prototype.some
, you can check if Name
value on arr1
item contains the arr2
item or not.
然后基于该 some()
结果,使用 Array.prototype.filter
,您可以按过滤
项. arr1
项arr2
And based on that some()
result, using Array.prototype.filter
, you can filter the arr1
items by arr2
items.
const arr1 = [{
"Failed": 0,
"Resume": false,
"Name": "GRP.Compiled.Release"
},
{
"Failed": 0,
"Resume": false,
"Name": "GPST.NonPermit.Inacitve"
},
{
"Failed": 0,
"Resume": false,
"Name": "PGVF.NonSubmit.Action"
},
{
"Failed": 0,
"Resume": false,
"Name": "PGVF.NonSubmit.Action"
}];
const arr2 = [{
"Name": "NonSubmit"
}, {
"Name": "NonPermit"
}];
const output = arr1.filter(({ Name }) => arr2.some((item) => Name.includes(item.Name)));
console.log(output);
这篇关于如何匹配字符串中的几个单词以过滤数组项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!