Всякий раз, когда вы имеете дело с чем-либо, что даже отдаленно напоминает дерево, вы, вероятно, захотите рекурсию.
Примерно так будет работать:
function getChildrenOf(input, target) {
let result = [target];
// recurse through children
if (input[target]) {
input[target].forEach(child => result = result.concat(getChildrenOf(input, child)));
}
return result;
}
const input = {
a: ['b', 'c'],
b: ['d', 'e'],
c: ['f', 'g'],
h: ['i', 'l'] // not gotten with a
}
console.log(getChildrenOf(input, 'a'))
По сути, пройдите один раз и добавьте саму цель, а затем переберите ее дочерние элементы и сложите их все вместе.
Если вы этого не хотитечтобы содержать a
сам, тогда вы можете использовать эту слегка измененную версию вместо:
function getChildrenOf(input, target, result) {
result = result || [];
// recurse through children
if (input[target]) {
input[target].forEach(child => {
result.push(child);
getChildrenOf(input, child, result)
});
}
return result;
}
const input = {
a: ['b', 'c'],
b: ['d', 'e'],
c: ['f', 'g'],
h: ['i', 'l'] // not gotten with a
}
console.log(getChildrenOf(input, 'a'))
console.log(getChildrenOf(input, 'b'))