简体   繁体   中英

convert nested tree JSON (parent Child) to an array of objects

I have an API which returns JSON tree format in parent/child relationship based on "ParentId" in each object. Below is the example of JSON

[
  {
    label: "parentA",
    children: [
      {
        label: "child A 1",
        children: [
          { label: "child A 1 - 1", value: "anonymous", children: [] },
        ],
      },
      {
        label: "child A 2",
        children: [{ label: "child A 2-1", children: [] }],
      },
    ],
  },
  {
    label: "parentB ",
    children: [
      {
        label: "child B 1",
        children: [{ label: "child B 1-1", children: [] }],
      },
    ],
  },
];

Which need to be converted into array of object where each object will represent the node element, with a unique primary key,Where "parentid" is null it will be root nodes and other will be child node of their parent node.

NOTE: the Id for each element should be unique

the final array of objects as bellow

[
  {
    id: 1,
    label: "parentA",
    parentId: null,
  },
  {
    id: 2,
    label: "child A 1 ",
    parentId: 1,
  },
  {
    id: 3,
    label: "child A 1 - 1",
    parentId: 2,
  },
  { id: 4, label: "child A 2", parentId: 1 },
  { id: 5, label: "child A 2-1", parentId: 4 },
  { id: 6, label: "child B", parentId: null },
  { id: 7, label: "child B 1", parentId: 6 },
  { id: 8, label: "child B 1-1", parentId: 7 },
];

my code is as below but the issue with it is returning the same id's for the elements which setting on the same level

      let index = 1;
        let parentID = result.rows[0].max;
        
    let pushInFinal = (root,parent) => {
        root.forEach((item) => {
          final_data.push({
            id: index ,
            label: item.label,
            parentId: parent,
          });
          if (item.hasOwnProperty("children")) {
            parentID = index++;
            pushInFinal(item.children, parentID);
          }
        });
      };
        pushInFinal(data, null);

This must be a new homework assignment.

To convert a tree into an array of nodes, you need a simple recursive tree-walk:

function flattenTree( tree ) {
  return [ ...enumerateNodes( tree ) ];
}

function *enumerateNodes( tree, parent  = { id: null } , id = 0 ) {

  // construct the flattened tree node
  const node = {
    ...tree,
    id: ++id,
    parentId: parent.id,
  };
  delete node.children;

  // then yield it
  yield node;

  // and then, recursively visit each child and yield its results:
  for (const childNode of tree.children) {
    yield *enumerateNodes(childNode, tree, id);
  }
  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM