In the front-end work, we often encounter places where we need to process data recursively. For example, when the back-end interface returns data and children is empty, use Element UI to cascade components, and the following figure will be displayed: The front end needs to delete the array with children as empty, so recursion is required.

Requirements, the effect is as follows:

The wrapper function clearallchildren.js

// Recursively clears the array where children under each element is empty
const clearAllChildren = (items, childrenName = 'children') = > {
  for (let i = 0; i < items.length; i++) {
    const item = items[i]
    // The current object has children
    if (item && item[childrenName]) {
        // Children is an empty array
      if (item[childrenName].length === 0) {
        delete item[childrenName]
      } else {
        // Recurse the current children array
        clearAllChildren(item[childrenName], childrenName)
      }
    }
  }
  return items
}

export default clearAllChildren
Copy the code