【问题标题】:Recursing a 1D nested array to update parent nodes递归一维嵌套数组以更新父节点
【发布时间】:2021-02-24 04:22:12
【问题描述】:

我有一个一维嵌套数组:

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(所有子代)。如何使用递归实现这一点?

注意:假设日期为时间戳

提前致谢

【问题讨论】:

  • 这个问题有点宽泛。您在尝试编码时遇到了什么问题?
  • 结构太平了,我都在努力写递归调用的函数

标签: javascript html vue.js recursion


【解决方案1】:

您需要的递归函数如下所示:

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>

Demo

【讨论】:

  • 我不会编写整个功能,但是这个最小 startDate 递归的伪实现应该可以为您提供入门所需的内容
  • 这个答案真的拯救了我的一天。非常感谢@Dan
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-06
  • 1970-01-01
  • 2018-05-28
相关资源
最近更新 更多