简体   繁体   English

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

[英]Convert array of objects with parent / child relationships to array of nested objects

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?如何在下面的示例代码中将table转换为看起来像transformedTable

Input data:输入数据:

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

You could nest a couple of loops to compare each object and add the "kids" property where needed. 您可以嵌套几个循环以比较每个对象,并在需要的地方添加“ kids”属性。 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM