我在React中有一个这样的数组。
{
"comments":[
{
"id":1,
"comment_text":"asdasdadasdsadsadadsa",
"author":"adsfasdasdsad",
"post_id":1,
"children":[]
},
{
"id":2,
"comment_text":"idlsfg",
"author":"asdsdasdad",
"post_id":1,
"children":[
{
"id":3,
"comment_text":"fdsfdsfdsfsdfsfsdf",
"author":"sdfdsfdsfdsfds",
"post_id":1,
"children":[
{
"id":4,
"comment_text":"fdsfdsfdsdsfdsfds",
"author":"sdfsdfdsfsdfdsfds",
"post_id":1,
"children":[
{
"id":5,
"comment_text":"sdfdsfdsfdsfdssdfsdfdsfdsfdsfds",
"author":"sdfsdfdsfdsfdsf",
"post_id":1,
"children":[]
},
{
"id":7,
"comment_text":"sdfdsfdsfdsfdssdfsdfdsfdsfdsfds",
"author":"sdfsdfdsfdsfdsf",
"post_id":1,
"children":[]
}
]
},
{
"id":6,
"comment_text":"fdsfdsfdsdsfdsfds",
"author":"sdfsdfdsfsdfdsfds",
"post_id":1,
"children":[]
}
]
}
]
}
]
}
现在,结果数组将是该父注释线程中最深注释的ID。结果应该只包含最深刻的评论
[[1], [5,7]]
现在,我使用递归来获取注释的深度,但是如何获取此数组?
答案 0 :(得分:1)
我们可以在这里使用递归
var obj ={
"comments":[
{
"id":1,
"comment_text":"asdasdadasdsadsadadsa",
"author":"adsfasdasdsad",
"post_id":1,
"children":[]
},
{
"id":2,
"comment_text":"idlsfg",
"author":"asdsdasdad",
"post_id":1,
"children":[
{
"id":3,
"comment_text":"fdsfdsfdsfsdfsfsdf",
"author":"sdfdsfdsfdsfds",
"post_id":1,
"children":[
{
"id":4,
"comment_text":"fdsfdsfdsdsfdsfds",
"author":"sdfsdfdsfsdfdsfds",
"post_id":1,
"children":[
{
"id":5,
"comment_text":"sdfdsfdsfdsfdssdfsdfdsfdsfdsfds",
"author":"sdfsdfdsfdsfdsf",
"post_id":1,
"children":[]
},
{
"id":7,
"comment_text":"sdfdsfdsfdsfdssdfsdfdsfdsfdsfds",
"author":"sdfsdfdsfdsfdsf",
"post_id":1,
"children":[]
}
]
},
{
"id":6,
"comment_text":"fdsfdsfdsdsfdsfds",
"author":"sdfsdfdsfsdfdsfds",
"post_id":1,
"children":[]
}
]
}
]
}
]
}
function getId(obj){
const {id, children } = obj
if(children && children.length){
return children.map(getId)
}
return id;
}
function getArrayDepth(value) {
return Array.isArray(value) ?
1 + Math.max(...value.map(getArrayDepth)) :
0;
}
var output = obj.comments.map(getId).map(k => {
if(Array.isArray(k)){
var d= getArrayDepth(k)
return k.flat(d-2).find(a => Array.isArray(a))
}
return [k]
})
console.log(otput)