gpt4 book ai didi

javascript - 如何让 child 进入圆形 map

转载 作者:行者123 更新时间:2023-12-03 01:41:32 25 4
gpt4 key购买 nike

也许我只是愚蠢,但我现在无法让它发挥作用。我尝试按照子属性数组获取对象内属性的所有子属性。它应该包括结构中向下的所有节点。

基本上,数组作为值,包含 map 中也存在的更多 Prop 。这是一种假树结构。

这是输入:

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 ..

最佳答案

每当您处理任何类似于树的事物时,您都可能需要递归。

像这样的东西会起作用:

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

关于javascript - 如何让 child 进入圆形 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50823418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com