Filtering Array of Objects with Arrays Based on Nested Value

Filtering array of objects with arrays based on nested value

This way you can go as deep as you want in an array and filter elements at any level,

arrayOfElements.map((element) => {
return {...element, subElements: element.subElements.filter((subElement) => subElement.surname === 1)}
})

Spread operator will expand element and then filtered subElements will override the subElements in element.

Filtering array of nested objects in JavaScript up to 'n' levels

You can do it with a recursive function and loop over only the valid subtasks. I do not think it needs much of an explanation, assuming you know what a recursive function is (and I guess you do):

function recurseOnSubTasks(elem) {
const filteredSubTasks = elem.subTasks
.filter(subTask => !subTask.endDate)
.map(subTask => recurseOnSubTasks(subTask))

return {
...elem,
subTasks: filteredSubTasks
}
}

And then call it with:

sampleData.map(elem => recurseOnSubTasks(elem))

var sampleData= [{       
"rowId": "3.0.0",
"startDate": "2020-10-20",
"subTasks": [
{
"rowId": "3.3.0",
"startDate": "2021-05-26",
"subTasks": [
{
"rowId": "3.3.0.1",
"startDate": "2021-05-26",
"subTasks": []
},
{
"rowId": "3.3.0.2",
"startDate": "2021-06-09",
"endDate": "2021-07-23",
"subTasks": []
},
]
},
]
}];

function recurseOnSubTasks(elem) {
const filteredSubTasks = elem.subTasks
.filter(subTask => !subTask.endDate)
.map(subTask => recurseOnSubTasks(subTask))

return {
...elem,
subTasks: filteredSubTasks
}
}

console.log(sampleData.map(elem => recurseOnSubTasks(elem)));

How to do filter on nested array of object in more than two level

You can use Array.prototype.filter, Array.prototype.some, and Array.prototype.find functions for achieving your required outcome. Try this-

const organisation=[{dept_id:1,dept:{name:"finance",employees:[{emp_id:1,name:"John",address:[{country:"US",state:"NC"}]}]}},{dept_id:2,dept:{name:"marketing",employees:[{emp_id:2,name:"David",address:[{country:"US",state:"NY"}]}]}},{dept_id:3,dept:{name:"sales",employees:[{emp_id:3,name:"Robert",address:[{country:"US",state:"NC"}]}]}}];

const filter = "NY";
const res = organisation.filter(
item => item.dept.employees.some(
employee => employee.address.find(address => address.state === filter)
)
);

console.log(res);

Filter an array of objects by key and nested value in JavaScript

This looks a little unwieldy but it's pretty simple. First, map your array and filter out any value.date that do not fit in the range. Then simply filter out any parent elements that have a zero-length value array.

const filteredEvents = (from, to) => allEvents
.map( g =>
({...g,
value: g.value.filter(f =>
new Date(f.date).getTime() >= new Date(from).getTime() &&
new Date(f.date).getTime() <= new Date(to).getTime())
}))
.filter(f => f.value.length>0);

let allEvents = [{
key: "Dec 2021",
value: [{
id: 0,
date: "Dec 06 2021"
},
{
id: 1,
date: "Dec 01 2021"
},
],
},
{
key: "Nov 2021",
value: [{
id: 0,
date: "Nov 27 2021"
},
{
id: 1,
date: "Nov 23 2021"
},
{
id: 2,
date: "Nov 10 2021"
},
],
},
{
key: "Oct 2021",
value: [{
id: 0,
date: "Oct 27 2021"
},
{
id: 1,
date: "Oct 23 2021"
},
{
id: 2,
date: "Oct 10 2021"
},
],
},
];

const filteredEvents = (from, to) => allEvents
.map( g => ({...g, value: g.value.filter(f => new Date(f.date).getTime() >= new Date(from).getTime() && new Date(f.date).getTime() <= new Date(to).getTime())})).filter(f => f.value.length>0);

console.log(filteredEvents("Nov 15 2021", "Dec 04 2021"));

Filter nested array in object array by array of values

If you're trying to filter the elements whose course IDs contain in the filter.courses, you may use Array#every and Array#includes to do that:

const data = [{"guid":"j5Dc9Z","courses":[{"id":3,"name":"foo"}]},{"guid":"a5gdfS","courses":[{"id":1,"name":"bar"},{"id":3,"name":"foo"}]},{"guid":"jHab6i","courses":[{"id":7,"name":"foobar"}]}];const courses = [1, 6, 3];
const r = data.filter(d => d.courses.every(c => courses.includes(c.id)));console.log(r);

How to filter array of nested objects with unknown depth based on given search term

I think you'll want something like this:

const filterByLabel = (array, searchTerm) => {
return array.reduce((prev, curr) => {
const children = curr.children ? filterByLabel(curr.children, searchTerm) : undefined;

return curr.label === searchTerm || children?.length > 0 ? [...prev, { ...curr, children }] : prev;
}, []);
}

filterByLabel(treeData, 'bananas');

How can I filter nested objects and arrays with JavaScript?

You can use filter and some

Here nested some is used to check whether any of dish_has_categories has CategoryId equal to '8', if it is true then we include that menu in final output else we don't

const data =[{ menuName: "Hot dogs", menu: [ { dishId: '1', dish_has_categories: [{ CategoryId: '8' }] }, { dishId: '2', dish_has_categories: [{ CategoryId: '9' }] }] }, { menuName: "Burgers", menu: [{ dishId: '3', dish_has_categories: [{ CategoryId: '6' }] }, { dishId: '4', dish_has_categories: [{ CategoryId: '4' }] }] }, { name: "Drinks", menu: [] } ]
let op = data.filter(val => { let menu = val.menu.some(({dish_has_categories}) => dish_has_categories.some(({CategoryId}) => CategoryId === '8')) return menu})
console.log('filtered values -->\n',op)
let names = op.map(({menuName})=> menuName)
console.log('Names --> \n', names)

Filter an array to return matching id's of a nested array in JavaScript

in your line

s.located_at.some((location) => location.id === client.location_id)

you have forgotten to return the results.

just change to

return s.located_at.some((location) => location.id === client.location_id)

const client = {
location_id:7
}

const staff = [{
contact_number: "4168455302",
email: "benshekhtman@hotmail.com",
first_name: "Ben",
id: 2,
last_name: "Shekhtman",
located_at: [
{id: 1, name: "Ben's Location"},
{id: 2, name: 'My second location'},
{id: 7, name: 'Medicare Clinic'},
],
provider_id: 2,
user_id: 2,
user_type: "ADMIN",
},
{
contact_number: "9053700017",
email: "test@email.com",
first_name: "Test ",
id: 3,
last_name: "Team Member",
located_at: [
{id: 3, name: 's'},
{id: 7, name: 'Medicare Clinic'},
],
provider_id: 2,
user_id: 7,
user_type: "SUPPORT",
}]

const filterStaffByLocation = staff.filter((s) => {
return s.located_at.some((location) => location.id === client.location_id)
})

console.log(filterStaffByLocation)
.as-console-wrapper { max-height: 100% !important; top: 0; }


Related Topics



Leave a reply



Submit