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