I have an array of complex objects which I need to filter based on multiple conditions
var myList= [
{
"UserId": 1,
"UserDetails": {
"Department": [
{
"Name": "dept1"
}
],
"Projects": [
{
"Name": "Project1"
},
{
"Name": "Project2"
}
]
}
},
{
"UserId": 2,
"UserDetails": {
"Department": [
{
"Name": "dept2"
}
],
"Projects": [
{
"Name": "Project3"
},
{
"Name": "Project4"
}
]
}
},
{
"UserId": 3,
"UserDetails": {
"Department": [
{
"Name": "dept3"
}
],
"Projects": [
{
"Name": "Project5"
},
{
"Name": "Project6"
}
]
}
}
]
I want to filter on two conditions either Department-->Name is "dept3" or there exist a project with Name->"Project3"
var filteredElements=this.myList.filter((x)=>x.UserDetails.filter((y)=>y.Department... ??
How can I write code to filter on these two conditions?
CodePudding user response:
To satisfy the condition
user belongs to a department "dept3"
user.UserDetails.Department.some(department => department.Name == "dept3")
there is a project named "Project3"
user.UserDetails.Projects.some(project => project.Name == "Project3")
Now chaining it together,
var filteredElements = this.myList.filter(user =>
user.UserDetails.Department.some(department => department.Name == "dept3") ||
user.UserDetails.Projects.some(project => project.Name == "Project3"))
CodePudding user response:
myList.filter(i => i.UserDetails.Department.some(d => d.Name === 'dept3') || i.UserDetails.Projects.some(p => p.Name === 'Project3'))
CodePudding user response:
You can't use the filter on UserDetails
as it is not an array but an object.
Apply find
on Department
and Projects
with OR condition between them with the required condition.
var myList= [
{
"UserId": 1,
"UserDetails": {
"Department": [
{
"Name": "dept1"
}
],
"Projects": [
{
"Name": "Project1"
},
{
"Name": "Project2"
}
]
}
},
{
"UserId": 2,
"UserDetails": {
"Department": [
{
"Name": "dept2"
}
],
"Projects": [
{
"Name": "Project3"
},
{
"Name": "Project4"
}
]
}
},
{
"UserId": 3,
"UserDetails": {
"Department": [
{
"Name": "dept3"
}
],
"Projects": [
{
"Name": "Project5"
},
{
"Name": "Project6"
}
]
}
}
]
var filteredElements = myList.filter(x =>x.UserDetails.Department.find(d => d.Name == "dept3") || x.UserDetails.Projects.find(p => p.Name == "Project3"))
console.log(filteredElements)