且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将具有父/子关系的对象数组转换为嵌套对象的数组

更新时间:2023-01-17 13:54:23

您可以嵌套几个循环以比较每个对象,并在需要时添加"kids"属性.然后,对结果数组进行过滤以仅保留最终的父级(其中包含所有嵌套子级).请参见下面的工作片段:

You could nest a couple of loops to compare each object and add the "kids" property where needed. Then, filter the resulting array to leave just the ultimate parents (which contain all the nested children). See working snippet below:

const table = [
  {id: 1, isMain: null, parentId: null, name:"john"},
  {id: 2, isMain: true, parentId: null, name:"sam"},
  {id: 3, isMain: null, parentId: 2, name:"samantha"},
  {id: 4, isMain: true, parentId: null, name:"kate"},
  {id: 5, isMain: true, parentId: 4, name:"jonathan"},
  {id: 6, isMain: null, parentId: 4, name:"walter"},
  {id: 7, isMain: null, parentId: 5, name:"clara"}
];

const kid = (p, c) => {
  if (p.hasOwnProperty('kids')) {
    p.kids.push(c);
  } else {
    p.kids = [c];
  }  
}

for (let i = 0; i < table.length - 1; i++) {
  let a = table[i];
  for (let j = i + 1; j < table.length; j++) {
    let b = table[j];
    if (a.id === b.parentId) {
      kid(a, b);
    } else if (b.id === a.parentId) {
      kid(b, a);
    }
  }
}

let result = table.filter(x => !x.parentId);
console.log(result);