There is an input array

blocks:[ { value: 1, parent: null }, { value: 2, parent: 0 }, { value: 3, parent: 1 }, { value: 4, parent: 2 }, { value: 5, parent: 1 } ] 

We need to convert it into a multi-dimensional array of this type.

 { value: 1, parent: null, children: [ { value: 2, parent: 0, children: [ { value: 3, parent: 1, children: [ { value: 4, parent: 2 } ] }, { value: 5, parent: 1 } ] } ] } 

Please tell me how to implement it on js?

  • 2
    Explain why value: 4 should be exactly in this place, and on what basis parent: 2 does it change to parent: 1 ? - Yaant
  • @Yaant I apologize, made a mistake, corrected. - G.Denis
  • parent is the index of the object, decided not to insert the id as a key value - G.Denis
  • Yeah, now it's more logical. But then why in the resulting object do you need the field parent , if the parent is uniquely determined by its structure itself? - Yaant
  • @Yaant agree you can remove it - G.Denis

2 answers 2

 let blocks = [{ value: 1, parent: null }, { value: 2, parent: 0 }, { value: 3, parent: 1 }, { value: 4, parent: 2 }, { value: 5, parent: 1 } ]; let res = []; JSON.parse(JSON.stringify(blocks)) // Ρ‡Ρ‚ΠΎΠ±Ρ‹ исходный массив остался Π½Π΅ΠΈΠ·ΠΌΠ΅Π½Π½Ρ‹ΠΌ, создаСм Π΅Π³ΠΎ копию, Π΄Π°Π»Π΅Π΅ Ρ€Π°Π±ΠΎΡ‚Π°Π΅ΠΌ с Π½Π΅ΠΉ. .forEach((item, i, arr) => { if (item.parent == null) { // элСмСнты Π±Π΅Π· родитСля добавляСм Π² Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚ΠΈΡ€ΡƒΡŽΡ‰ΠΈΠΉ массив res.push(item); } else { let parent = arr[item.parent]; // Π½Π°Ρ…ΠΎΠ΄ΠΈΠΌ Ρ€ΠΎΠ΄ΠΈΡ‚Π΅Π»ΡŒΡΠΊΠΈΠΉ элСмСнт Π² исходном массивС (Π²Π΅Ρ€Π½Π΅Π΅, Π² Π΅Π³ΠΎ ΠΊΠΎΠΏΠΈΠΈ) if (!parent.children) parent.children = []; parent.children.push(item); // ΠΈ добавляСм ΠΊ Π½Π΅ΠΌΡƒ Π΄ΠΎΡ‡Π΅Ρ€Π½ΠΈΠΉ элСмСнт } delete item.parent; // удаляСм ΠΏΠΎΠ»Π΅ parent }); console.log(res); 

  • Thank you very much - G. Denis

Firstly, this is not a multidimensional array, but a tree Secondly, convert the data through the Array.map() method to the format { id, parentId } , since { value, parent } not a very good naming. After that stop this function and you will get the desired result.

 function list_to_tree(list) { var map = {}, node, roots = [], i; for (i = 0; i < list.length; i += 1) { map[list[i].id] = i; // initialize the map list[i].children = []; // initialize the children } for (i = 0; i < list.length; i += 1) { node = list[i]; if (node.parentId !== "0") { // if you have dangling branches check that map[node.parentId] exists list[map[node.parentId]].children.push(node); } else { roots.push(node); } } return roots; }; var entries = [ { "id": "12", "parentId": "0" }, { "id": "10", "parentId": "12" }, ]; console.log(list_to_tree(entries));