我有一个包含以下数据的 object。如何使用递归函数获取标题键中的所有数据?
I have an object that contains the following data. How can I get all the data in the title key using the recursive function?
我有一个包含以下数据的 object。如何使用递归函数获取标题键中的所有数据?
我想要一个函数 return 一个包含 a, b, c, d, e, f
的数组
{
children: [
{
children: [
{
children: [],
title: "a"
}
],
title: "b"
},
{
children: [
{
children: [],
title: "c"
},
{
children: [],
title: "d"
}
],
title: "e"
}
],
title: "f"
}
你可以这样做:
function drill(t, n) {
if (n.length > 0) {
for (let elem of n) {
t.push(elem.title);
drill(t, elem.children)
}
}
return t
}
正如@rickhg12hs 所做的那样
遵循使用现代语法的解决方案。 extractTitles
递归生成标题数组,只要有 children 并将它们缩减为单个数组。
const extractTitles = (arr) =>
arr.reduce((prev, { children, title }) => [...prev, title, ...(children.length ? extractTitles(children) : [])], []);
extractTitles(tree);
或者您可以使用 flatmap
.
const extractTitles = ({ title, children = [] }) =>
[title, ...children.flatMap(extractTitles)];
extractTitles(tree);
// ["f","b","a","e","c","d"]
我有一个包含以下数据的 object。如何使用递归函数获取标题键中的所有数据? 我想要一个函数 return 一个包含 a, b, c, d, e, f
的数组{
children: [
{
children: [
{
children: [],
title: "a"
}
],
title: "b"
},
{
children: [
{
children: [],
title: "c"
},
{
children: [],
title: "d"
}
],
title: "e"
}
],
title: "f"
}
你可以这样做:
function drill(t, n) {
if (n.length > 0) {
for (let elem of n) {
t.push(elem.title);
drill(t, elem.children)
}
}
return t
}
正如@rickhg12hs 所做的那样
遵循使用现代语法的解决方案。 extractTitles
递归生成标题数组,只要有 children 并将它们缩减为单个数组。
const extractTitles = (arr) =>
arr.reduce((prev, { children, title }) => [...prev, title, ...(children.length ? extractTitles(children) : [])], []);
extractTitles(tree);
或者您可以使用 flatmap
.
const extractTitles = ({ title, children = [] }) =>
[title, ...children.flatMap(extractTitles)];
extractTitles(tree);
// ["f","b","a","e","c","d"]