我有以下数据结构
tasks = [{
id: 1,
name: "task1",
subtasks: [
{
id: 4,
name: "task2",
subtasks: [{
id: 11,
name: "task to remove",
completed: false
}]
},
{
id: 6,
name: "task to remove",
subtasks: []
},
{
id: 7,
name: "parent task to keep",
subtasks: [{
id: 11,
name: "task to keep",
completed: true
}]
}
]
},
{
id: 44,
name: "task to keep",
subtasks: [{
id: 55,
name: "task to keep",
completed: true
},
{
id: 66,
name: "task to delete",
completed: false
}
]
}
]
由于嵌套级别不受限制,只有叶任务的标志已完成,我只需要过滤掉那些已完成的任务并将其保留在其父任务中。
我查看了lodash,但它似乎没有深层过滤器。我现在正在考虑使用树遍历来过滤任务。
有没有一种简单的方法可以用 lodash 实现这样的事情?
最佳答案
您想要一个 lodash 解决方案。我相信这个递归函数可以解决问题。
function completed (task) {
// if it is a leaf node, just return true when it is completed
if (_.has(task,'completed')) {
return task.completed;
}
// if it has subtasks, then use our filter on all the subtasks ...
if (_.has(task,'subtasks')) {
task.subtasks = _.filter(task.subtasks, completed);
// ... and only return true if there are subtasks left after filtering
return task.subtasks.length;
}
}
console.log(_.filter(tasks,completed));
关于Javascript实现嵌套json数据的深度过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45798564/