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

时间:2018-10-05 12:16:39

标签: javascript arrays object nested

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

输入数据:

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"}
]

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

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"
      },
    ]
  },
]

1 个答案:

答案 0 :(得分:1)

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

    OkPacket {
        fieldCount: 0,
        affectedRows: 1,
        insertId: 0,
        serverStatus: 2,
        warningCount: 0,
        message: '',
        protocol41: true,
        changedRows: 0 
    }