过滤对象的嵌套数组

时间:2019-10-29 03:03:47

标签: javascript reactjs ecmascript-6

如何过滤这种数组?我想根据我的情况对其进行过滤

enter image description here

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;

2 个答案:

答案 0 :(得分:1)

想法:

  • 将嵌套数组简化为简单数组
  • 从简单数组中过滤结果

方法I:简洁明了

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

方法II:使用库(例如Ramda)对其进行展平

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

查看实时结果here

方法III:手动执行:

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);

答案 1 :(得分:0)

有关更多信息,请参见Array.prototype.flat()Array.prototype.filter()

// 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)