扁平化数组转树,求最优方案
我们看下题目:
const data = [
{
"_id": "2d44d6c26110d22203f5fbf95484b816",
"comment_content": "测试评论",
"article_id": "cd045e756102b0b600e6153e7dc3e678",
"comment_author": {
"name": "用户97.89556629736191",
"email": "用户52.8973290551612@github.com"
}
},
{
"_id": "14139e126110d75503f2df4a0354e831",
"comment_content": "第二条评论",
"article_id": "cd045e756102b0b600e6153e7dc3e678",
"comment_author": {
"name": "用户27.064798298154493",
"email": "用户97.70539438271202@github.com"
}
},
{
"_id": "cd045e7561121d9404c02e1a61856780",
"comment_content": "大萨达",
"article_id": "8937eaa96102b10200bc97bd4e2c6183",
"comment_author": {
"name": "用户45.88242116867542",
"email": "用户36.95435829054714@github.com"
}
},
{
"_id": "14139e1261129806045420e93a9a9922",
"comment_content": "二级评论",
"reply_content": "二级评论",
"pid": {
"_id": "2d44d6c26110d22203f5fbf95484b816",
"comment_content": "测试评论",
"article_id": "cd045e756102b0b600e6153e7dc3e678",
"comment_author": {
"name": "用户97.89556629736191",
"email": "用户52.8973290551612@github.com"
}
},
"comment_author": {
"name": "用户79.29663107058975",
"email": "用户63.831949036364335@github.com"
}
}
]
输出结果
const data = [
{
"_id": "2d44d6c26110d22203f5fbf95484b816",
"comment_content": "测试评论",
"article_id": "cd045e756102b0b600e6153e7dc3e678",
"comment_author": {
"name": "用户97.89556629736191",
"email": "用户52.8973290551612@github.com"
},
children: [
{
"_id": "14139e1261129806045420e93a9a9922",
"comment_content": "二级评论",
"reply_content": "二级评论",
"pid": {
"_id": "2d44d6c26110d22203f5fbf95484b816",
"comment_content": "测试评论",
"article_id": "cd045e756102b0b600e6153e7dc3e678",
"comment_author": {
"name": "用户97.89556629736191",
"email": "用户52.8973290551612@github.com"
}
},
"comment_author": {
"name": "用户79.29663107058975",
"email": "用户63.831949036364335@github.com"
}
}
]
},
{
"_id": "14139e126110d75503f2df4a0354e831",
"comment_content": "第二条评论",
"article_id": "cd045e756102b0b600e6153e7dc3e678",
"comment_author": {
"name": "用户27.064798298154493",
"email": "用户97.70539438271202@github.com"
},
children: []
},
{
"_id": "cd045e7561121d9404c02e1a61856780",
"comment_content": "大萨达",
"article_id": "8937eaa96102b10200bc97bd4e2c6183",
"comment_author": {
"name": "用户45.88242116867542",
"email": "用户36.95435829054714@github.com"
},
children: []
},
]
要求:
时间二十分钟,所有代码全部手写,不能用除了原生之外的第三方代码。
加强版:
1、树表联动。改动树或表其中一个数据,另一个数据也可以随之改变
最后
希望大佬们能给个最优方案,在评论里发出来,互相探讨(进去喝了三杯茶没写出来)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
//数据
//方法
//结果
加强版:
1、树表联动。改动树或表其中一个数据,另一个数据也可以随之改变
二级评论项塞入 pid 对应项的 children 里就行了。