猿问

递归一维嵌套数组以更新父节点

我有一个一维嵌套数组:


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: []}

]

根据上述数据结构,树视图taskName如下所示


-> Parent

        -> Child one

                   -> SubChild one

        -> Child two

这是我的问题:当我更新startDate一个孩子的 时,它的直接父母startDate应该用(所有孩子的)最小值进行更新startDate,并且这个过程应该传播到根。对于(即) (其所有子项)的endDate最大值,反之亦然。startDate我如何使用递归来实现这一点?


红糖糍粑
浏览 116回答 1
1回答

繁花不似锦

您需要的递归函数将如下所示:methods: {&nbsp; &nbsp; adjustParent(item) {&nbsp; &nbsp; &nbsp; if (!item.parentId) return;&nbsp; &nbsp;// top-level, exit&nbsp; &nbsp; &nbsp; const parent = this.nestedObj.find(o => o.id === item.parentId);&nbsp; &nbsp; &nbsp; const children = this.nestedObj.filter(o => o.parentId === item.parentId);&nbsp; &nbsp; &nbsp; parent.startDate = Math.min.apply(null, children.map(o => o.startDate));&nbsp; &nbsp; &nbsp; this.adjustParent(parent);&nbsp; // recurse&nbsp; &nbsp; }}change例如,您可以调用它:<div v-for="item in nestedObj">&nbsp; <input type="text" v-model="item.startDate" @change="adjustParent(item)" /></div>演示
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答