Multi-level nested object array - find out the id of each parent it belongs to according to the innermost id

Using recursion can reduce the amount of code without being limited by the array level.

Use the find method to reduce the number of array loops.

Array format:

let a = [
  {
    id: 2,
    hasChildren: true,
    children: [
      {
        id: 5,
        hasChildren: true,
        children: [
          {
            id: 3,
            hasChildren: false,
          },
          {
            id: 4,
            hasChildren: false,
          },
        ],
      },
    ],
  },
];

method:

function get_level_all(data, id, arr = []) {
      data.find((item) => {
        if (item.id === id) {
          arr.push(item.id);
          return true;
        } else if (item.hasChildren && item.children.length) {
          arr = get_level_all(item.children, id, arr);
          if (arr.length) {
            arr.push(item.id);
            return true;
          } else {
            return false;
          }
        }
        return false;
      });
      return arr;
}

transfer:

get_type_level_all(a, 4) //返回 [4, 5, 2]

Guess you like

Origin blog.csdn.net/qq_18676843/article/details/122428363