The original data:
[{'name': 'Layer 1'.'pid': '0'.'id': '11'.'children': [{'name': 'Layer 1 layer 2 layer 1'.'pid': '11'.'id': '111'.'children': [{'name': 'Layer 1 layer 2 Layer 3 layer 1'.'pid': '111'.'id': '1111'
},
{
'name': 'Layer 1 layer 2 Layer 2 Layer 3'.'pid': '111'.'id': '1112'}]}, {'name': 'Layer 1 layer 2'.'pid': '11'.'id': '112'
},
{
'name': 'Layer 1 layer 2 layer 3'.'pid': '11'.'id': '113'}]}, {'name': 'Layer 1 2'.'pid': '0'.'id': '12'.'children': [{'name': 'Layer 1 layer 2 Layer 2 layer 1'.'pid': '12'.'id': '121'
},
{
'name': 'Layer 1 2 Layer 2'.'pid': '12'.'id': '122'}}]]Copy the code
Method encapsulation:
function flatten (data, level = 0) {
return data.reduce((arr, { name, pid, id, children = []}) = >
arr.concat([{ name, pid, id, level}], flatten(children, level + 1)), [])}Copy the code
Processed data:
[{"name":"Layer 1"."pid":"0"."id":"11"."level":0},
{"name":"Floor 1, floor 2, floor 1"."pid":"11"."id":"111"."level":1},
{"name":"Floor 1, floor 2, floor 1, floor 3"."pid":"111"."id":"1111"."level":2},
{"name":"Floor 1, floor 2, floor 1, floor 3"."pid":"111"."id":"1112"."level":2},
{"name":"Floor 1, floor 2"."pid":"11"."id":"112"."level":1},
{"name":"Floor 1, floor 2, floor 3"."pid":"11"."id":"113"."level":1},
{"name":"Layer 1 2"."pid":"0"."id":"12"."level":0},
{"name":"Floor 1, floor 2, floor 2, floor 1"."pid":"12"."id":"121"."level":1},
{"name":"Floor 1, floor 2, floor 2"."pid":"12"."id":"122"."level":1}]Copy the code