gwy*_*ing 1 javascript arrays recursion object javascript-objects
我这里有一段代码,我想识别最后一个元素paragraph 3
并添加一些文本,例如 - last item
输出为paragraph 3 - last item
.
我更喜欢它是否是递归的,因为对象中的子级数量没有限制。
obj = {
content: [
{ text: "paragraph 1" },
{
content: [
{ text: "paragraph 2" },
]
},
{ text: "paragraph 3" },
]
}
Run Code Online (Sandbox Code Playgroud)
另一个例子是这样的,它的输出应该是paragraph 5 - last item
obj = {
content: [
{ text: "paragraph 1" },
{
content: [
{ text: "paragraph 2" }
]
},
{ text: "paragraph 3" },
{
content: [
{ text: "paragraph 4" },
{
content: [
{ text: "paragraph 5" }
]
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
小智 5
一个简单的实现。检查键名,如果它是内容,它会用最后一个元素来回忆自己。否则,它会返回它。
const obj1 = {
content: [{
text: "paragraph 1"
}, {
content: [{
text: "paragraph 2"
}]
}, {
text: "paragraph 3"
}]
};
const obj2 = {
content: [{
text: "paragraph 1"
},
{
content: [{
text: "paragraph 2"
}]
}, {
text: "paragraph 3"
},
{
content: [{
text: "paragraph 4"
},
{
content: [{
text: "paragraph 5"
}]
}
]
}
]
}
function getLatestParagraph(obj) {
for (const key in obj) {
if (key === "content") return getLatestParagraph(obj[key].pop());
return obj[key];
}
}
console.log(getLatestParagraph(obj1))
console.log(getLatestParagraph(obj2))
Run Code Online (Sandbox Code Playgroud)