这里有无穷无尽的树问题,但对我来说,如果有人能帮助我解决这个具体问题,那就太好了。我为我的新兵训练营进行了一次“模拟面试”,这是一个问题。我没有一个好的方法来处理它..
const people = {
name: "Robin",
children: [
{
name: "Alberto",
children: [
{
name: "Quinn",
children: [
{
name: "Conner",
children: []
},
{
name: "Lila",
children: []
}
]
}
]
},
{
name: "Charlie",
children: []
}
]
}
// Write a function called getNames that returns a string "Robin, Alberto, Quinn, Conner, Lila, Charlie
当您尝试学习这些东西时,尤其是当您筛选大量问题,而这些问题的解决 Angular 各不相同时,这可能会让人不知所措。因此,我们将不胜感激在此方面的帮助!
最佳答案
一种方法是使用具有递归方法的reduce
方法,其中您concat
reduce 的输出到初始name
string.f
const people = {"name":"Robin","children":[{"name":"Alberto","children":[{"name":"Quinn","children":[{"name":"Conner","children":[]},{"name":"Lila","children":[]}]}]},{"name":"Charlie","children":[]}]}
function getNames(data, name = "") {
return data.name + (data.children ?
data.children.reduce((r, e) => {
return r + ", " + getNames(e)
}, "") : "")
}
console.log(getNames(people))
另一种递归解决方案是使用 map
和 flatten
方法,您可以在其中选择所有名称,然后使用 join
将它们转换为字符串方法。
const people = {"name":"Robin","children":[{"name":"Alberto","children":[{"name":"Quinn","children":[{"name":"Conner","children":[]},{"name":"Lila","children":[]}]}]},{"name":"Charlie","children":[]}]}
function getString({ name, children }) {
return [name, ...children.map(getString).flat()].join(', ')
}
const result = getString(people)
console.log(result)
关于javascript - 从树结构中抓取所有 "names",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52412090/