简体   繁体   中英

Filter nested array of objects

How can I filter this kind of array? I want to filter it based on my condition below

在此处输入图像描述

let employeeLeaves = isEmployeeLeave;

const calendarDates = value.toString();
const formatCalendarDates = moment(calendarDates).format('YYYY-MM-DD');

const filteredData = employeeLeaves.filter(function(item) {
 return item.startDate == formatCalendarDates;
});

return filteredData;

Idea:

  • flatten the nested array into an simple array
  • filter the result from the simple array

Method I: Quick and concise

const result = [].concat(...input).filter(item =>  item.startDate === formatCalendarDates);

Method II: Using a library (eg Ramda) to flatten it

R.flatten(data).filter(item => item.key === 'a');

See the live result here .

Method III: do it manually:

 const data = [ [ { key: 'a', value: 1 }, { key: 'b', value: 2 }, { key: 'c', value: 3 }, { key: 'a', value: 4 }, { key: 'b', value: 5 }, { key: 'a', value: 6 } ], [ { key: 'b', value: 7 }, { key: 'b', value: 8 }, { key: 'a', value: 9 } ], [ { key: 'c', value: 10 }, { key: 'b', value: 11 }, { key: 'b', value: 12 } ] ]; const flat = data => { let output = []; data.map(arr => output = [... arr, ... output]); return output; } const result = flat(data).filter(item => item.key === 'a'); console.log(result);

Since you've posted no data, I just dummied up an array of array of objects which seems to be what you're dealing with

The concept should help

 const data = [ [ { key: 'a', value: 1 }, { key: 'b', value: 2 }, { key: 'c', value: 3 }, { key: 'a', value: 4 }, { key: 'b', value: 5 }, { key: 'a', value: 6 } ], [ { key: 'b', value: 7 }, { key: 'b', value: 8 }, { key: 'a', value: 9 } ], [ { key: 'c', value: 10 }, { key: 'b', value: 11 }, { key: 'b', value: 12 } ] ]; const result = data.map(arr => arr.filter(item => item.key === 'a')).filter(arr => arr.length); console.log(result);

See Array.prototype.flat() and Array.prototype.filter() for more info

 // Input. const employees = [[{id: '4930'}], [{id: '4328'}]] // Predicate. const matchingIdPredicate = (employee, id) => employee.id === id // Filter. const employeesWithMatchingId = employees.flat(1).filter(employee => matchingIdPredicate(employee, '4930')) // Proof. console.log('Employees with matching id:', employeesWithMatchingId)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM