javascript - 从 Javascript 中的递归函数返回对象数组

标签 javascript function object recursion

我正在研究递归函数。

我必须将所有具有键“data: true”的对象推送到数组中。 函数中间的 console.log 为我提供了单独数组中的所有这些对象。

但我无法返回末尾带有对象的数组。 我究竟做错了什么? 谢谢

const entries = {
  root: {
    data: true,
    key: "root",
    text: "some text"
  },
  test: {
    one: {
      two: {
        data: true,
        key: "test.one.two",
        text: "some text.again"
      },
      three: {
        data: true,
        key: "test.one.three",
        text: "some.more.text"
      }
    },
    other: {
      data: true,
      key: "test3",
      text: "sometext.text"
    }
  },
  a: {
    b: {
      data: true,
      key: "a.b",
      text: "a.b.text"
    },
    c: {
      d: {
        data: true,
        key: "a.c.d",
        text: "some.a.c.d"
      }
    }
  }
};


function recursiveFunc(data) {
  let tab = [];
  for (let property in data) {
    if (data.hasOwnProperty(property)) {
      if (data[property].data === true) {
        tab.push(data[property]);
        console.log("t", tab);
      } else {
        recursiveFunc(data[property])
      }
    }
  }
  return tab
}

console.log(recursiveFunc(entries));

最佳答案

在递归调用上添加 tab.concat() 以连接递归 fn 返回的项目。

const entries = {
  root: {
    data: true,
    key: "root",
    text: "some text"
  },
  test: {
    one: {
      two: {
        data: true,
        key: "test.one.two",
        text: "some text.again"
      },
      three: {
        data: true,
        key: "test.one.three",
        text: "some.more.text"
      }
    },
    other: {
      data: true,
      key: "test3",
      text: "sometext.text"
    }
  },
  a: {
    b: {
      data: true,
      key: "a.b",
      text: "a.b.text"
    },
    c: {
      d: {
        data: true,
        key: "a.c.d",
        text: "some.a.c.d"
      }
    }
  }
};


function recursiveFunc(data) {
  let tab = [];
  for (let property in data) {
    if (data.hasOwnProperty(property)) {
      if (data[property].data === true) {
        tab.push(data[property]);
        console.log("t", tab);
      } else { 
        tab = tab.concat(recursiveFunc(data[property]));
      }
    } 
  } 
  return tab
}
console.log(recursiveFunc(entries));

关于javascript - 从 Javascript 中的递归函数返回对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53429174/

相关文章:

postgresql - 循环 CopyTo 查询

Javascript - 循环类并添加函数

excel - vba 简单范围/对象错误

php - 具有循环引用的对象上的 in_array

javascript - jQuery - 如何在ajax化表单时获取提交类型输入的值

javascript - 缩放固定宽度的字体以适应一行中恒定数量的字符

javascript - 在不重新刷新页面的情况下使用 ES6 时,事件监听器不会重新附加到我的 HTML 元素

javascript - 无法在对象上使用reduce 获得平均成绩(JavaScript)

javascript - 如何不区分大小写包含使用 lodash 进行搜索

javascript - 是删除对函数的引用,还是删除函数的实例?