也许我只是愚蠢但我现在无法让它发挥作用。 我尝试将一个属性的所有子项都放在一个对象中,跟随一系列子道具。它应该包括结构中所有节点。
基本上数组作为值,包含更多也存在于地图中的道具。它是一种假树结构。
这是输入:
const input = {
a: ["b", "c"],
b: ["d", "e"],
c: ["f", "g"]
}
作为输出,我期望像getChildrenOfProp(input, "a")
之类的函数调用的结果导致:
getChildrenOfProp(input, "a");
// results in ["b", "c", "d", "e", "f", "g"]
// because "b" & "c" are present in map and have more children ..
getChildrenOfProp(input, "b");
// results in ["d", "e"]
// no more children because "d" & "e" are not present in the map ..
答案 0 :(得分:1)
每当你处理任何甚至模糊地类似于树的东西时,你可能会想要递归。
这样的事情会起作用:
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'))