Home > Back-end >  Get all parents for object in nested array JS
Get all parents for object in nested array JS

Time:05-27

I have a problem on a project using vuejs. I have an array of nested object like this :

Data

data: [
  {
    "id":1,
    "parent_id":null,
    "title":"First folder",
    "children":[
       {
          "id":3,
          "parent_id":1,
          "title":"First folder in parents",
          "children":[]
       },
       {
          "id":4,
          "parent_id":1,
          "title":"Second folder in parents",
          "children":[
             {
               "id":5,
               "parent_id":4,
               "title":"test",
               "children":[]
             }
           ],
       }
    ]
  },
  {
    "id":2,
    "parent_id":null,
    "title":"Second folder",
    "children":[],
  }
]

And I would like to get an array of all parents for a specific id in a computed property

    computed: {
      parents() { 
        this.getAllParents(data, currentId);
      },
    },

And my function

        getParents(array, id, parentsId) {
        for (let i = 0; i < array.length; i  ) {
            const child = array[i];
            if (child.id === id && ((child.children.length > 0 && child.children.some((el) => el.id === parentsId)) || !parentsId)) {
                return [child];
            } if (child.children.length > 0) {
                const x = this.getParents(child.children, child.id, id);

                if (x) return Array.isArray(x) ? [child, ...x] : [child, x];
            }
        }
        return [];
    },

For example, if my currentId is 3, I would like this in my computed:

[
  {"id": 1, "parent_id": null....},
  {"id": 3, "parent_id": 1....}
]

If my currentId is 1, I would like this :

[
  {"id": 1, "parent_id": null....},
]

If my currentId is 5, I would like this :

[
  {"id": 1, "parent_id": null....},
  {"id": 4, "parent_id": 1....},
  {"id": 5, "parent_id": 4....},
]

Now, my function

return [
  {"id": 1, "parent_id": null....},
  {"id": 4, "parent_id": 1....}
] 

if my current id is 3, not id:3 and I can't understand why

How to do this please ?

Thanks

CodePudding user response:

You can recursively loop over the children array and keep collecting the parents.

Refer to the solution below:

const data = [
  {
    id: 1,
    parent_id: null,
    title: "First folder",
    children: [
      { id: 3, parent_id: 1, title: "First folder in parents", children: [] },
      {
        id: 4,
        parent_id: 1,
        title: "Second folder in parents",
        children: [{ id: 5, parent_id: 4, title: "test", children: [] }],
      },
    ],
  },
  { id: 2, parent_id: null, title: "Second folder", children: [] },
];

const getAncestors = (target, children, ancestors = []) => {
  for (let node of children) {
    if (node.id === target) {
      return ancestors.concat(node.id);
    }
    const found = getAncestors(target, node.children, ancestors.concat(node.id));
    if (found) {
      return found;
    }
  }
  return undefined;
};

console.log(getAncestors(5, data));

Note: I've just pushed the ids for brevity, you can update the solution to push the entire nodes.

CodePudding user response:

function getAllParents(arr, id, res) {
  for (const el of arr) {
    if (el.id == id) {
      res.unshift(el);
      return true;
    } else {
      let is_parent = getAllParents(el.children, id, res);
      if (is_parent) {
        res.unshift(el);
        return true;
      }
    }
  }
}

const res = [];
getAllParents(data, 2, res);
console.log(res);
  • Related