How to filter and checked matches conditionally with multiple fields passing in string; i have a request as like below:
{
name: "abc",
email: "",
phone: "123456",
match: "phone"
}
In that case i have to filtered array and get match phone objects in response and i have an array as like below
[{name: "abc", email: "[email protected]",phone:"123456"}, {name: "abc", email: "[email protected]", phone:"1236"}, {name: "pqr", email: "[email protected]", phone:"123456"} ]
in that case my expected output as like below
[{name: "abc", email: "[email protected]",phone:"123456"}, {name: "pqr", email: "[email protected]", phone:"123456"} ]
Note: my filter condition would be change as per the match string it could be on
1st request type
{
email: "[email protected]",
phone: "123456",
match: "phone,email"
}
Result:
[{name: "pqr", email: "[email protected]", phone:"123456"}]
2nd request type
{
name: "abc",
email: "[email protected]",
phone: "1236",
match: "phone,email"
}
Result:
[ {name: "abc", email: "[email protected]", phone:"1236"}]
name,phone or phone or email or name,email,phone or name only
in that case i have to manipulate filter based on match string
CodePudding user response:
Even though I don't understand 100% of your question, I believe that the code below can help you.
const data = [
{name: "abc", email: "[email protected]",phone:"123456"},
{name: "abc", email: "[email protected]", phone:"1236"},
{name: "pqr", email: "[email protected]", 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)
CodePudding user response:
You can define a function, filterArr(arr, cond)
that can be used to test every condition on the fields specified by condition.match
property as follows:
const
input = [{name: "abc", email: "[email protected]",phone:"123456"}, {name: "abc", email: "[email protected]", phone:"1236"}, {name: "pqr", email: "[email protected]", phone:"123456"} ],
cond1 = {name: "abc", email: "", phone: "123456", match: "phone"},
cond2 = {email: "[email protected]", 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 );