JSFiddle - React, Tailwind, and code Playground

Flatten children

by Hugo Carneiro

JavaScript

var tmp = [];

function flatten (data) {
	data.forEach(function (i) {
  	tmp.push(i);
    if (i.children) {
    	flatten(i.children)
    }
  });
}

var data = [
	{
    title: 'Header',
    children: [{
      title: 'Paragraph',
      children: [{
        title: 'Span',
        children: []
      }]
    }],
  },
  {
    title: 'Container',
    children: [{
      title: 'Paragraph',
      children: []
    }]
  }
];

flatten(data);
console.log(tmp);

/* EXPECTED RESULT */
/*
[
	{
    title: 'Header',
    children: [{
      title: 'Paragraph',
      children: []
    }],
  },
  {
    title: 'Paragraph',
    children: []
  },
  {
    title: 'Container',
    children: [{
      title: 'Paragraph',
      children: []
    }]
  },
  {
    title: 'Paragraph',
      children: []
  }
];
*/