[英]Find first occurrence of an object with property in tree-like structure
I have a structure like this: 我有这样的结构:
[{
description: 'Beef Stew',
complete: false,
tasks: [{
description: 'Cut vegetables',
complete: false,
tasks: [{
description: 'Dice carrots',
complete: false
}, {
description: 'Mince Garlic',
complete: false
}, {
description: 'Prepare potatoes',
complete: false,
tasks: [{
description: 'Peel potatoes',
complete: false
}, {
description: 'Cut potatoes',
complete: false
}]
}]
}]
}]
In this case, I am looking for the first occurance of an element with no tasks that is not complete . 在这种情况下,我正在寻找没有完成任务的元素的第一次出现 。 In this case, that means it should be { description: 'Dice carrots', completed: false }
. 在这种情况下,这意味着它应该是{ description: 'Dice carrots', completed: false }
。 Here is the basic of what I have written. 这是我写的基本内容。 codepen here too . 也是这里的代码 。
function next(steps) {
return steps.reduce((r, step) => {
return (step.tasks && step.tasks.length > 0 && !step.complete) ? next(step.tasks) : step;
}, []);
}
This does get a deep step, but it ends up getting the last step. 这确实迈出了一大步,但它最终迈出了最后一步。 How can I make an algorithm that will get the first? 如何制作能够获得第一个算法?
I would use Array.prototype.find() 我会使用Array.prototype.find()
The mozilla site provides a polyfill implementation of this. mozilla站点提供了polyfill实现。
Applying it to your problem: 将它应用于您的问题:
var matchingStep = steps.find(function(step) {
return !(step.tasks.find(function(task) { return !(task.complete); });
});
I got a pretty good solution in my Steps
class, for if anyone is looking for the answer in the future. 我在Steps
课程中得到了一个非常好的解决方案,因为如果有人在将来寻找答案的话。
class Steps {
constructor(steps) {
this.steps = steps;
this.current = steps;
}
next(steps=this.steps) {
for(let step of steps) {
if (step.tasks instanceof Array && !step.complete) {
return this.next(step.tasks);
}
return this.current = step;
}
}
}
This allows me to advance the step forward recursively. 这允许我递归地前进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.