Flattening Array of Objects with nested children and saving the level

September 4, 2023 · 1 min readLucian Ciobanu
Tags:JavaScript

So I had a big challenge today to make nested objects into an array I could use as data source for a kendo ui table. the challenge was also to save the level of the children to display them with a bit of an indent. The recursive function which helped me here is the one below. I actually didn't use parentId and main as I didn't need them.

function flatten(data, depth = 0, parentId = null, main = []) {
  return data.reduce((r, { items, id, ...rest }) => {
    const obj = { ...rest, id, depth, parentId, main }
    r.push(obj)
    
    if (items.length) {
      r.push(...flatten(items, depth + 1, id, [...main, id]))
    }
    
    return r;
  }, [])
}

const result = flatten(data)
console.log(result)

Linke to the article on stack overflow: https://stackoverflow.com/questions/64727886/recursive-function-to-flatten-nested-array-and-keeping-track-of-all-parent-nodes

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery