Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Nhận mảng đối tượng và chuyển JSON thành cấu trúc cây trong JavaScript

Giả sử chúng ta có mảng đối tượng như sau:

const arr = [ 
  { 
    "parentIndex": '0' , 
    "childIndex": '3' , 
    "parent": "ROOT", 
    "child": "root3" 
  }, 
  { 
    "parentIndex": '3' , 
    "childIndex": '2' , 
    "parent": "root3" , 
    "child": "root2" 
  }, 
  { 
    "parentIndex": '3' , 
    "childIndex": '1' , 
    "parent": "root3" , 
    "child": "root1" 
  } 
];

Chúng ta cần viết hàm JavaScript nhận vào mảng này. Hàm sử dụng đệ quy và chuyển JSON trên thành cấu trúc cây (Tree-structure).

Cấu trúc cây trông như sau:

nodeStructure: { 
  text: { name: "root3" }, 
  children: [ 
    { 
      text: { name: "root2" } 
    }, 
    { 
      text: { name: "root1" } 
    } 
  ] 
} };

Ví dụ

Mã thực hiện:

const arr = [ 
  { 
    "parentIndex": '0' , 
    "childIndex": '3' , 
    "parent": "ROOT", 
    "child": "root3" 
  }, 
  { 
    "parentIndex": '3' , 
    "childIndex": '2' , 
    "parent": "root3" , 
    "child": "root2" 
  }, 
  { 
    "parentIndex": '3' , 
    "childIndex": '1' , 
    "parent": "root3" , 
    "child": "root1" 
  } 
]; 
const partial = (arr = [], condition) => { 
  const result = []; 
  for (let i = 0; i < arr.length; i++) { 
    if(condition(arr[i])){ 
      result.push(arr[i]); 
    } 
  } 
  return result; 
} 
const findNodes = (parentKey,items) => { 
  let subItems = partial(items, n => n.parent === parentKey); 
  const result = []; 
  for (let i = 0; i < subItems.length; i++) { 
    let subItem = subItems[i]; 
    let resultItem = { 
      text: {name:subItem.child} 
    }; 
    let kids = findNodes(subItem.child , items); 
    if(kids.length){ 
      resultItem.children = kids; 
    } 
    result.push(resultItem); 
  } 
  return result; 
} 
console.log(JSON.stringify(findNodes('ROOT', arr), undefined, 4));

Kết quả

Kết quả in ra console:

[ 
  { 
    "text": { 
      "name": "root3" 
    }, 
    "children": [ 
      { 
        "text": { 
          "name": "root2" 
        } 
      }, 
      { 
        "text": { 
          "name": "root1" 
        } 
      } 
    ] 
  } 
]