我有一个数据数组,我想将整个 commentId
与 JavaScript 相加。
const comments = [
{
commentId: 1,
commentContent: 'Hai',
replies: [
{
commentId: 11,
commentContent: 'Hai juga',
replies: [
{
commentId: 111,
commentContent: 'Haai juga hai jugaa'
},
{
commentId: 112,
commentContent: 'Haai juga hai jugaa'
}
]
},
{
commentId: 12,
commentContent: 'Hai juga',
replies: [
{
commentId: 121,
commentContent: 'Haai juga hai jugaa'
}
]
}
]
},
{
commentId: 2,
commentContent: 'Halooo'
}
]
例如:假设有commentId [1, 2, 11, 12, 111, 112, 121]
。因此,commentId.length
是 7
回答1
你需要通过递归函数来做到这一点。因为评论和回复之间可以有 n 层嵌套。看看下面的代码。
function caluclateLength(commentsOrReplies, sum=0) {
sum += commentsOrReplies.length
return commentsOrReplies.reduce((total, commentorReply) => (total + caluclateLength(commentorReply.replies || [])), sum)
}
console.log(comments) // should return desired result