javascript 如何有条件地筛选和检查多个字段的匹配项

e5nszbig  于 2023-02-02  发布在  Java
关注(0)|答案(3)|浏览(147)

如何过滤和检查匹配条件与多个字段传入字符串;我有如下要求:

{
name: "abc",
email: "",
phone: "123456",
match: "phone"
}

在这种情况下,我必须过滤数组,并在响应中获得匹配的电话对象,我有一个如下所示的数组

[{name: "abc", email: "abc@gmail.com",phone:"123456"}, {name: "abc", email: "abc@gmail.com", phone:"1236"}, {name: "pqr", email: "pqr@gmail.com", phone:"123456"} ]

在这种情况下,我的预期输出如下所示

[{name: "abc", email: "abc@gmail.com",phone:"123456"}, {name: "pqr", email: "abc@gmail.com", phone:"123456"} ]

注意:我的过滤条件将根据匹配字符串进行更改

1st request type
{
email: "pqr@gmail.com",
phone: "123456",
match: "phone,email"
}

Result:
[{name: "pqr", email: "pqr@gmail.com", phone:"123456"}]

2nd request type
{
name: "abc",
email: "abc@gmail.com",
phone: "1236",
match: "phone,email"
}

Result:
[ {name: "abc", email: "abc@gmail.com", phone:"1236"}]

姓名、电话或电话或电子邮件或仅姓名、电子邮件、电话或姓名
在这种情况下,我必须基于匹配字符串来操作过滤器

68bkxrlz

68bkxrlz1#

尽管我不能100%理解你的问题,但我相信下面的代码可以帮助你。

const data = [
  {name: "abc", email: "abc@gmail.com",phone:"123456"}, 
  {name: "abc", email: "abc@gmail.com", phone:"1236"}, 
  {name: "pqr", email: "pqr@gmail.com", phone:"123456"} 
]

const options = {
  name: "abc",
  email: "",
  phone: "123456",
  match: "phone"
}

function filter(data,options){
    const keys = options.match.split(',')
    return data
    .filter(item=>{
        return keys
        .map(key=>item[key] === options[key])
        .every(check => check)
    })
}

const test = filter(data,options)

console.log(test)
rslzwgfq

rslzwgfq2#

您可以定义函数filterArr(arr, cond),该函数可用于测试condition.match属性指定的字段上的每个条件,如下所示:

const
      input = [{name: "abc", email: "abc@gmail.com",phone:"123456"}, {name: "abc", email: "abc@gmail.com", phone:"1236"}, {name: "pqr", email: "pqr@gmail.com", phone:"123456"} ],
      
      cond1 = {name: "abc", email: "", phone: "123456", match: "phone"},
      
      cond2 = {email: "pqr@gmail.com", phone: "123456", match: "phone,email"},
      
      filterArr = (arr, cond) => arr.filter(item => cond.match.split(',').every(c => cond[c] === item[c])),
      
      output1 = filterArr(input,cond1),
      
      output2 = filterArr(input,cond2);
      
console.log( output1 );
console.log( output2 );
nkkqxpd9

nkkqxpd93#

据我所知,您希望根据filter对象的match属性中可用的filterObject属性从数组中筛选出对象。
如果我的理解是正确的,您可以借助Array.filter()方法和Array.every()
现场演示**:**

const arr = [
  {name: "abc", email: "abc@gmail.com", phone:"123456"}, 
  {name: "abc", email: "abc@gmail.com", phone:"1236"},
  {name: "pqr", email: "pqr@gmail.com", phone:"123456"}
];

const filterObj = {
  email: "pqr@gmail.com",
  phone: "123456",
  match: "phone,email"
};

const matchFilterFields = filterObj.match.split(',');

const res = arr.filter(obj => {
  return matchFilterFields.every(field => filterObj[field] === obj[field])
});

console.log(res);

相关问题