将具有父/子关系的对象数组转换为嵌套对象的数组 [英] Convert array of objects with parent / child relationships to array of nested objects

查看:61
本文介绍了将具有父/子关系的对象数组转换为嵌套对象的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将一个对象数组转换为另一个嵌套对象数组时遇到问题.如何在下面的示例代码中将 table 转换为类似于 transformedTable ?

I have a problem transforming an array of objects to another array of nested objects. How can I transform table to look like transformedTable in the example code 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"}
]

我想将上面的数据转换为这样的内容:

I want to transform the data above to something like this:

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

推荐答案

您可以嵌套几个循环以比较每个对象,并在需要时添加"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);

这篇关于将具有父/子关系的对象数组转换为嵌套对象的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆