【发布时间】:2018-10-04 11:42:00
【问题描述】:
我有一个评论/回复对象,我一直在尝试以对象数组的格式创建一个新对象,但这超出了我的技能水平,我目前只是一个学生
这是我要转换的对象:
[
{"id":9,"comment":"This is a normal comment to the post SON","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null},
{"id":22,"comment":"new made comment","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null},
{"id":23,"comment":"just let me ","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null},
{"id":24,"comment":"bla bla","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null},
{"id":29,"comment":"another comment","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null},
{"id":30,"comment":"reply 12 btw","commentername":"noforget","parentID":29,"commentVotes":0,"isWhat":"reply","voteToID":null,"votername":null,"voteAmount":null},
{"id":31,"comment":"reply btw","commentername":"noforget","parentID":9,"commentVotes":0,"isWhat":"reply","voteToID":null,"votername":null,"voteAmount":null},
{"id":32,"comment":"reply to reply btw","commentername":"noforget","parentID":31,"commentVotes":0,"isWhat":"reply","voteToID":null,"votername":null,"voteAmount":null}
]
这是我希望它最终的格式:
[
[
{"id":9,"comment":"This is a normal comment to the post SON","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null},
{"id":31,"comment":"reply btw","commentername":"noforget","parentID":9,"commentVotes":0,"isWhat":"reply","voteToID":null,"votername":null,"voteAmount":null},
{"id":32,"comment":"reply to reply btw","commentername":"noforget","parentID":31,"commentVotes":0,"isWhat":"reply","voteToID":null,"votername":null,"voteAmount":null}
],
[
{"id":22,"comment":"new made comment","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null}
],
[
{"id":23,"comment":"just let me ","commentername":"noforget","parentID":42,"commentVotes":0,"isWhat":"comment","voteToID":null,"votername":null,"voteAmount":null}
]
]
换句话说,我希望将主要评论及其所有回复(以及这些回复的回复等)放入数组中,该数组位于数组中
关于数据的几点说明,"isWhat"可以是"comment"或"reply",如果是评论,则表示只是对帖子的普通评论而不是回复,@987654326其中@ 是帖子的ID(您不必担心),"isWhat: reply" 的parentID 是它正在回复的评论的parentID
感谢您的宝贵时间!
【问题讨论】:
-
到目前为止你有什么尝试?
-
@NicoHaase 我想可能会遍历它们,存储第一条评论的 ID,找到该 ID 的 parentID,我认为 reduce 方法是我需要的,我看了一些视频就可以了,但无法完成我所需要的。
-
不要过度设计 :) 如果减少听起来太复杂,找到你自己的方法来解决它。我认为不需要行业级解决方案 - 自行解决并发现您的解决方案对您的学习过程具有很高的价值
-
@NicoHaase 我花了 2 天时间尝试不同的解决方案,这就是我在这里问这个的原因,我真的需要帮助哈哈
-
那就看看Máté给出的答案吧。这有帮助吗?算法看起来没那么复杂
标签: javascript algorithm sorting recursion data-manipulation