Skip to content

Tree to Array

Converts a tree structure array into a flat array.

Parameters

It takes two parameters:

  • Tree: Tree structure array

  • Options: An optional parameter object used to configure the specific behavior of the conversion method

    PropertyDescriptionTypeDefault
    addFieldsList of field names to be added and their corresponding property value calculation methods[{ fieldName: string;callback: (item) => any }][]
    childrenKeyKey name for child nodesstring'children'
    ignoreFieldsList of field names to be ignoredstring[][]
    needParentIdWhether to add the parent node ID to the node informationbooleantrue
    primaryKeyPrimary key name for nodebooleantrue

Example

javascript
const treeArray = [
  {
    id: '1',
    name: 'Node 1',
    list: [
      {
        id: '2',
        name: 'Node 2',
        list: [
          {
            id: '3',
            name: 'Node 3'
          }
        ]
      },
      {
        id: '4',
        name: 'Node 4'
      }
    ]
  }
];
const calculateDepth = (node) => {
  let depth = 0;
  let parent = node;
  while (parent) {
    depth++;
    parent =
      parent['parentId'] && treeArray.find((n) => n.id === parent['parentId']);
  }
  return depth;
};
const options = {
  childrenKey: 'list',
  ignoreFields: [],
  addFields: [
    {
      fieldName: 'hasChildren', // Add a new 'field' property with a boolean value
      callback: (node) => Boolean(node['children'])
    },
    {
      fieldName: 'depth', // Add a new 'depth' property with the depth of each node
      callback: calculateDepth
    }
  ],
  needParentId: true
};

const flatArray = treeToArray(treeArray, options);

console.log(flatArray);

[ { "id": "1", "name": "Node 1", "parentId": "", "hasChildren": false, "depth": 1 }, { "id": "2", "name": "Node 2", "parentId": "1", "hasChildren": false, "depth": 1 }, { "id": "3", "name": "Node 3", "parentId": "2", "hasChildren": false, "depth": 1 }, { "id": "4", "name": "Node 4", "parentId": "1", "hasChildren": false, "depth": 1 } ]

Released under the MIT License.