【问题标题】:Order list of object based on parent child association in JSJS中基于父子关联的对象排序列表
【发布时间】:2021-03-10 23:56:35
【问题描述】:

我正在尝试创建一个循环,该循环将遍历对象数组并以某种方式对它们进行排序,如果对象是父对象的子对象,则将其放入子数组中,然后从中删除原始对象名单。我有它的工作,但它对孩子的孩子等失败。如果它的父对象已经是另一个对象的子对象,它将失败。我该如何修改它以完成上述操作?

这是我所拥有的:

for (const obj of objects) {
  const children = objects.filter(d => d.parentId === obj.id);
  obj.children = children;

  for (const child of children) {
    const objIndex = objects.findIndex(d => d.id === child.id);
    if (objIndex > -1) objects.splice(objIndex, 1);
  }
}

所以如果输入是:

const objects = [
  { id: 85, parentId: null },
  { id: 86, parentId: 85 },
  { id: 87, parentId: 86 },
  { id: 88, parentId: 86 }
];

结果应该是:

[
  {
    id: 85, children: [
      {
        id: 86, children: [
          { id: 87 },
          { id: 88 }
        ]
      }
    ]
  }
];

但我得到的不是:

[
  { id: 85, children: [{ id: 86 }]},
  { id: 87 },
  { id: 88 },
]

我明白为什么会发生这种情况我只是不确定如何解决它,因为从技术上讲你可以无限嵌套。这里有什么想法吗?

【问题讨论】:

标签: javascript


【解决方案1】:

我会遍历每个节点,找到父节点并将自己添加到父节点的子节点中。

然后过滤掉非根节点(具有 parentId 的节点)。

const objects = [
  { id: 85, parentId: null },
  { id: 86, parentId: 85 },
  { id: 87, parentId: 86 },
  { id: 88, parentId: 86 }
];

let hierarchy = objects.map(obj=>({...obj}));

for(let i=0;i<hierarchy.length;i++){
  const cur=hierarchy[i];
  if(cur.parentId){
    const parent = hierarchy.find(({id})=>id===cur.parentId);
    parent.children = [...(parent.children || []), cur];
  }
}

hierarchy=hierarchy.filter(({parentId})=>!parentId);


console.log(hierarchy);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多