紅糖糍粑
2023-07-29 16:40:45
我有一個一維嵌套數組: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我如何使用遞歸來實現這一點?
1 回答

繁花不似錦
TA貢獻1851條經驗 獲得超4個贊
您需要的遞歸函數將如下所示:
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
}
}
change例如,您可以調用它:
<div v-for="item in nestedObj">
<input type="text" v-model="item.startDate" @change="adjustParent(item)" />
</div>
添加回答
舉報
0/150
提交
取消