There is a piece of JSON, as follows:
According to the tree hierarchy, it is level 3. I now want to return to the first two levels and discard the third level. How can I use javascript code to achieve this?
Original structure:
[{
'id': 1,
'title': 'node1',
'nodes': [
{
'id': 11,
'title': 'node1.1',
'nodes': **[
{
'id': 111,
'title': 'node1.1.1',
'nodes': []
}**
]
},
{
'id': 12,
'title': 'node1.2',
'nodes': []
}
]
}, {
'id': 2,
'title': 'node2',
'nodes': [
{
'id': 21,
'title': 'node2.1',
'nodes': []
},
{
'id': 22,
'title': 'node2.2',
'nodes': []
}
]
}, {
'id': 3,
'title': 'node3',
'nodes': [
{
'id': 31,
'title': 'node3.1',
'nodes': []
}
]
}]
Processed structure:
[{
'id': 1,
'title': 'node1',
'nodes': [
{
'id': 11,
'title': 'node1.1',
**'nodes': []**
},
{
'id': 12,
'title': 'node1.2',
'nodes': []
}
]
}, {
'id': 2,
'title': 'node2',
'nodes': [
{
'id': 21,
'title': 'node2.1',
'nodes': []
},
{
'id': 22,
'title': 'node2.2',
'nodes': []
}
]
}, {
'id': 3,
'title': 'node3',
'nodes': [
{
'id': 31,
'title': 'node3.1',
'nodes': []
}
]
}]
It is more convenient to use recursion for tree operations
depth is the number of reserved layers. Note that it is called for the node of that layer.
'id': 1,
You can just loop through the two levels of json and reassemble a new json.