Ian
Ian

Reputation: 87

Recursive search for the object's parent array using for loop

data=[
      {
        id: 1,
        name: "Model",
        type: "directory",
        path: "/path/to/folder",
        children: [
          {
            id: 2,
            name: "model.yaml",
            type: "file",
            path: "../../storage/model.yaml",
          },
        ],
      },
      {
        id: 3,
        name: "Inventory",
        type: "directory",
        path: "/path/to/folder",
        children: [
          {
            id: 4,
            name: "inventory.yaml",
            type: "file",
            path: "../../storage/inventory.yaml",
          },
        ],
      },
      {
        id: 5,
        name: "UI",
        type: "directory",
        path: "/path/to/folder",
        children: [
          {
            id: 6,
            name: "elements",
            type: "directory",
            path: "../../storage",
          },
          {
            id: 7,
            name: "viewmodel",
            type: "directory",
            path: "../../storage",
          },
          {
            id: 8,
            name: "i18n",
            type: "directory",
            path: "../../storage",
          },
          {
            id: 9,
            name: "index.template.html",
            type: "file",
            path: "../../storage/index.template.html",
          },
        ],
      },
      {
        id: 10,
        name: "DeviceConnector",
        type: "directory",
        children: [],
      },
];


function getParent(data, id) {
    for (let i = 0; i < data.length; i++) {
        if (data[i].id === id) {
          return data;
        } else if (data[i].children && data[i].children.length) {
          return data[i].children;
        } else if (data[i].children && data[i].children.length) {
          getParent(data[i].children, id);
        }
    }
}

I would to make a recursive search for the object's parent array using for loop. My problem is that the loop is stopping when finding the first children occurence. Looking for a way to fix the function and make the work of it possible on any nested level.

What I'm trying to do is by calling, for example getParent(data,4), to get a parent array with one element of id = 4.

Upvotes: 1

Views: 365

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386522

You could store the result of a recursive call and if the value is truthy, you could exit the loop with the found array.

function getParent(data, wanted) {
    for (const { id, children } of data) {
        if (id === wanted) return data;

        const temp = children && getParent(children, wanted);
        if (temp) return temp;
    }
}

Upvotes: 1

Related Questions