Yesterday encountered an interview problem, handwritten JS to convert the JSON array into a tree object, yesterday wrote wrong, today deliberately think of the next, the idea is actually quite simple, loop + recursive, Get child node object.
1 Let data = [2 {' parent_id ': 0, ' id ': 1, ' value ': ' XXX '},3 {' parent_id ': 1, ' ID ': 3, ' value ': ' xxx '},4 {' parent_id ': 4, ' ID ': 6, ' value ': ' xxx '}, C11>5 {' parent_id ': 3, ' ID ': 5, ' value ': ' XXX '},6 {' parent_id ': 2, ' ID ': 4, ' Value ': ' xxx '},7 {' parent_id ': 1, ' ID ': 2, ' value ': ' xxx '},8 ]
The main methods are as follows, using the ES6 syntax
1Let Totree = (arr, key = ' id ', Pkey = ' pid ', children= ' children ') = = {2 if(Arr.length = = 0){3 return {}4 }5 returnGetChildren (arr, 0)//the 0 here represents the root node, if the root node identifier is ' # ', then here is ' # '6 7 //The main principle is to find the parent node parent_id as the PID of the object, and then one layer down to find the child node ID, see if there is parent_id equals ID of the object8 functionGetChildren (arr, pid) {9Let temp = {}TenArr.foreach (v = { One if(V[pkey] = = =pid) { ATemp[v[key]] = {}//This can be adjusted to suit your needs - if(Object.keys (GetChildren (arr, V[key)). Length!== 0) {//If there are child nodes, the recursive method can also be extracted here to reduce the amount of code and the Operation -Temp[v[key]][children] = GetChildren (arr, V[key])//This can be adjusted to suit your needs the } - } - }) - returnTemp + } -}
Test data
1Let tree =totree (data)2 Console.log (Json.stringify (tree))3 4 //The result is:5 {6"1": {7"Children": {8"2": {9"Children": {Ten"4": { One"Children": { A"6": {} - } - } the } - }, -"3": { -"Children": { +"5": {} - } + } A } at } -}
JS converts a JSON array into a tree object