我有一个嵌套的数据 struct ,我想创建一个递归函数,给定一个对象的name参数,它将返回父对象的name参数.

然而,有几个相关的问题,答案并不能解释为什么我的function getParentName不工作.

为什么getParentName不起作用?

const nestedData = {
  name: "parent",
  children: [{ name: "child", children: [{ name: "grandchild" }] }],
};

function getParentName(nested, name) {
  if (nested.children && nested.children.map((d) => d.name).includes(name)) {
    return nested.name;
  } else if (nested.children) {
    nested.children.forEach((child) => {
      return getParentName(child, name);
    });
  }
  return undefined; //if not found
}

//The parent of "grandchild" is "child" - but the function returns undefined
const parentName = getParentName(nestedData, "grandchild");

为什么这个函数找不到父函数?

推荐答案

你的答案的问题是.forEach忽略了return的值.你的else if分店没有return分店..forEach只用于副作用.考虑使用生成器,它更容易表达你的解决方案.

function* getParentName({ name, children = [] }, query) {
  for (const child of children)
    if (child.name === query)
      yield name
    else
      yield *getParentName(child, query)
}

const data = {
  name: "parent",
  children: [{ name: "child", children: [{ name: "grandchild" }] }],
}

const [result1] = getParentName(data, "grandchild")
const [result2] = getParentName(data, "foobar")
const [result3] = getParentName(data, "parent")

console.log("result1", result1)
console.log("result2", result2)
console.log("result3", result3)

如果没有找到匹配的 node ,或者匹配的 node 没有父 node ,则答案为undefined-

result1 child
result2 undefined
result3 undefined

请注意,捕获单个结果需要[].这是因为生成器可以返回1个或多个值.如果不喜欢这种语法,可以编写一个泛型first函数,只获取生成器中的第一个值-

function first(it) {
  for (const v of it)
    return v
}
const result1 = first(getParentName(data, "grandchild"))
const result2 = first(getParentName(data, "foobar"))
const result3 = first(getParentName(data, "parent"))

这种方法的优点很多.您的try 使用.map.includes,这两个都会在children之间完全迭代.在另一个分支中,使用.forEach,它也穷尽地迭代所有children.这种方法避免了不必要的.map.includes,但也在读取第一个值后停止immediately.

Javascript相关问答推荐

如何在react js中显示文本字段或2个不同的组件?

ChartJS:分组堆叠条形图渲染错误

导入图像与内联包含它们NextJS

错误:找不到react-redux上下文值;请确保该组件包装在React原生Expo应用程序中的提供者中

单击按钮后未清除 Select

为什么JavaScript双边字符串文字插值不是二次的?

可以的.是否可以在不预编译的情况下使用嵌套 Select 器?

如何将连续的十六进制字符串拆分为以空间分隔的十六进制块,每个十六进制块包含32个二元组?

Cookie中未保存会话数据

Phaser 3 console. log()特定游戏角色的瓷砖属性

我应该绑定不影响状态的函数吗?'

为什么我的列表直到下一次提交才更新值/onChange

如何让npx在windows中运行js脚本?

在我的html表单中的用户输入没有被传送到我的google表单中

使用POST请求时,Req.Body为空

如何在Angular17 APP中全局设置AXIOS

Eval vs函数()返回语义

使用VUE和SCSS的数字滚动动画(&;内容生成)

在VS代码上一次设置多个变量格式

自定义图表工具提示以仅显示Y值