gpt4 book ai didi

javascript - 合并评论中的回复。回复也可以有回复

转载 作者:行者123 更新时间:2023-11-30 12:43:56 24 4
gpt4 key购买 nike

我有一组评论。这是一个示例评论:

{
"author": "John",
"text": "Hi there",
"replies":
[
{
"author": "Henry",
"text": "Hi John, did you get me that paper?",
"replies":
[
{
"author": "John",
"text": "Which one?",
"replies":
[
{
"author": "Henry",
"text": "Never mind. Let's catch up later"
},
{
"author": "Frank",
"text": "The analysis sheet we talked about at the last meeting man!",
"replies":
[
{
"author": "John",
"text": "Oh that! Let me get back to you by the end of the day"
}
]
}
]
}
]
},
{
"author": "Barry",
"text": "Call me about that last years report please when you find the time",
"replies":
[
{
"author": "John",
"text": "About 5 good?",
"replies":
[
{
"author": "Barry",
"text": "Yes, thank you"
}
]
}
]
}
]
}

我如何将每个评论的回复扁平化为一个单一的回复数组,所以它看起来像这样:

{
"author": "John",
"text": "Hi there",
"replies":
[
{
"author": "Henry",
"text": "Hi John, did you get me that paper?"
},
{
"author": "John",
"text": "Which one?"
},
{
"author": "Henry",
"text": "Never mind. Let's catch up later"
},
{
"author": "Frank",
"text": "The analysis sheet we talked about at the last meeting man!"
},
{
"author": "John",
"text": "Oh that! Let me get back to you by the end of the day"
},
{
"author": "Barry",
"text": "Call me about that last years report please when you find the time"
},
{
"author": "John",
"text": "About 5 good?"
},
{
"author": "Barry",
"text": "Yes, thank you"
}
]
}

最佳答案

function get_replies(currentObject, result) {
result.push({
author: currentObject.author,
text: currentObject.text
});
if (currentObject.replies) {
for (var i = 0; i < currentObject.replies.length; i += 1) {
get_replies(currentObject.replies[i], result);
}
}
return result;
}

console.log(get_replies(data, []));

输出

[ { author: 'John', text: 'Hi there' },
{ author: 'Henry', text: 'Hi John, did you get me that paper?' },
{ author: 'John', text: 'Which one?' },
{ author: 'Henry', text: 'Never mind. Let\'s catch up later' },
{ author: 'Frank',
text: 'The analysis sheet we talked about at the last meeting man!' },
{ author: 'John',
text: 'Oh that! Let me get back to you by the end of the day' },
{ author: 'Barry',
text: 'Call me about that last years report please when you find the time' },
{ author: 'John', text: 'About 5 good?' },
{ author: 'Barry', text: 'Yes, thank you' } ]

关于javascript - 合并评论中的回复。回复也可以有回复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23308242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com