简体   繁体   中英

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?

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. 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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