Amaarockz
Amaarockz

Reputation: 4674

Recursing a 1D nested array to update parent nodes

I have a 1D nested array:

nestedObj: [
   { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 2, parentId: 1, taskCode: '12100', taskName: 'Child one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 3, parentId: 2, taskCode: '12200', taskName: 'SubChild one', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []},
   { id: 4, parentId: 1, taskCode: '12200', taskName: 'Child two', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}
]

As per the above data structure, the tree view with taskName is stated below

-> Parent
        -> Child one
                   -> SubChild one
        -> Child two

Here is my question: when I update the startDate of a child, its immediate parent's startDate should be updated with the minimum startDate (of all its children) and this process should propagate till the root. And the vice versa for endDate (ie) the maximum startDate (of all its children). How can I achieve this using recursion?

Note: Assume the dates to be timestamps

Thanks in advance

Upvotes: 1

Views: 134

Answers (1)

Dan
Dan

Reputation: 63059

The recursive function you need will look something like this:

methods: {
    adjustParent(item) {
      if (!item.parentId) return;   // top-level, exit

      const parent = this.nestedObj.find(o => o.id === item.parentId);
      const children = this.nestedObj.filter(o => o.parentId === item.parentId);

      parent.startDate = Math.min.apply(null, children.map(o => o.startDate));

      this.adjustParent(parent);  // recurse
    }
}

You could call it on change for example:

<div v-for="item in nestedObj">
  <input type="text" v-model="item.startDate" @change="adjustParent(item)" />
</div>

Demo

Upvotes: 1

Related Questions