【问题标题】:Filter nested array of objects过滤嵌套的对象数组
【发布时间】:2019-10-29 03:03:47
【问题描述】:

如何过滤这种数组?我想根据我下面的条件过滤它

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;

【问题讨论】:

  • 您知道有什么比在问题中放置数据图片更好的方法吗?将一些数据放入问题中 - 看起来您有一个嵌套数组,因此您需要过滤第二级数组,而不是第一级
  • 查看所需输出的样本会很有帮助。另外,您附加的代码的状态是什么?是不是没有完成,或者输出的格式与您预期的不同?

标签: javascript reactjs ecmascript-6


【解决方案1】:

想法:

  • 将嵌套数组展平为一个简单数组
  • 从简单数组中过滤结果

方法一:快速简洁

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

方法二:使用库(例如 Ramda)将其展平

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

查看实时结果here

方法三:手动:

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

【讨论】:

    【解决方案2】:

    请参阅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)

    【讨论】:

    • 感谢您的回答。我已经从@David的回答中得到了它
    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 2020-03-08
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    相关资源
    最近更新 更多