の配列がありcomments
ます。これらのコメントの一部は、実際には 内の他のノードのサブコメントですcomments
。すべてcomment
にはnum_comments
、、、parent_id
およびid
属性があります。コメントの数が 0 より大きい場合、コメントにサブコメントがあることはわかっています。
サブコメントを親コメント内に配置し、サブコメントを配列から削除したいと考えています。外側の for ループが完了した後、配列内に子コメントが存在してはならずcomments
、各子コメントはその親コメントの subcomments
配列に移動されます。
問題は、このコードが実行された後、すべてのアイテムcomments
が削除され、次のようになることです。
未定義のプロパティ 'item' を読み取れません
(これはcomments
空の結果です。)
私が問題を抱えているコードは次のとおりです。
for comment in comments
if comment.item.num_comments > 0
comment.item.subcomments = [] unless comment.item.subcomments
for comment_second in comments # Goes through a second time to find subcomments for the comment
if comment_second.item.parent_id == comment.item.id
comment.item.subcomments.push(comment_second)
comments.splice(comments.indexOf(comment_second), 1)
編集:
以下の答えはうまくいきませんでしたが、間違いなく正しい方向への一歩でした. 私はコードを少しいじりました。私が考えているのは、temp_comment.item.subcomment
s が配列として定義されていないということです。これにより、プッシュされないエラーが発生します。これが説明していないのは、配列から何も削除されていないことです。
temp_comments = comments.slice(0)
for comment in comments
for comment_second in comments
temp_comment = temp_comments[temp_comments.indexOf(comment)]
temp_comment.item.subcomements = [] unless temp_comment.item.subcomments?
if comment_second.item.parent_id == comment.item.id
temp_comment.item.subcomments.push(comment_second)
temp_comments.splice(temp_comments.indexOf(comment_second), 1)
comments = temp_comments
以前と同じエラー メッセージが表示されます
2回目の編集:
エラーは実際には[] is not a function