How to create a recursive nested array from flat data in JavaScript?

I’m seeking guidance on how to construct a deeply nested data structure in JavaScript. I have a dataset formatted like this:

const inputData = [
  ["Planet", "Continent", "Country", "Region", "Population"],
  ["Planet", "Continent", "City", "City-Country", "1000"],
  ["Planet", "Continent-Country", "Sector", "Sector-Country", "500"],
  // additional data...
];

The challenge is that each row can have a varying number of columns, and I want to transform it into a structure similar to this:

const desiredStructure = [
  {
    name: "Planet",
    children: [
      {
        name: "Continent",
        children: [
          {
            name: "Region",
            value: 1000
          }
        ]
      }
    ]
  }
];

The process requires iterating through the provided rows and nesting the data correspondingly, placing the ‘value’ as the last element in each row whenever there are no further child nodes. I’m feeling a bit overwhelmed with recursion and would appreciate any assistance to clarify how to structure this effectively.

Here’s a concise solution using recursion to transform your flat data into a nested structure:

function createNestedStructure(data) {
  const result = [];
  data.forEach(row => {
    let currentLevel = result;
    row.forEach((value, index) => {
      if (index === row.length - 1) return; // Skip the population part here.

      let existing = currentLevel.find(item => item.name === value);
      if (!existing) {
        existing = { name: value, children: [] };
        currentLevel.push(existing);
      }

      if (index === row.length - 2) {
        existing.children.push({ name: row[index + 1], value: +row[index + 2] });
      } else {
        currentLevel = existing.children;
      }
    });
  });
  return result;
}

const inputData = [
  ["Planet", "Continent", "Country", "Region", "1000"],
  ["Planet", "Continent", "City", "City-Country", "1000"],
  ["Planet", "Continent-Country", "Sector", "Sector-Country", "500"],
  // additional data...
];

console.log(JSON.stringify(createNestedStructure(inputData), null, 2));

This code iteratively constructs the nested structure, using the last value as the value attribute.

To transform your flat data into a recursive nested array in JavaScript, you can utilize a recursive function to build the nested structure. The strategy involves iterating over each row of your data, inserting nodes into the nested structure where needed, and assigning values when reaching the last element of a row. Here’s a step-by-step approach:

  1. Initialize the Data Structure: Start with an empty array that will contain the nested data.
  2. Iterate Through the Rows: Process each row individually, building paths dynamically.
  3. Use Recursion: Employ a helper function to traverse and build the nested structure recursively.

Below is an example that achieves the desired transformation:

const inputData = [
  ["Planet", "Continent", "Country", "Region", "Population"],
  ["Planet", "Continent", "City", "City-Country", "1000"],
  ["Planet", "Continent-Country", "Sector", "Sector-Country", "500"]
];

function buildTree(data) {
  const tree = [];

  data.forEach(path => {
    let currentLevel = tree;
    path.forEach((name, index) => {
      if (index === path.length - 2) { // Assume penultimate element is the final named node
        let value = parseInt(path[index + 1]);
        currentLevel.push({ name, value });
      } else if (index < path.length - 2) {
        let existing = currentLevel.find(item => item.name === name);
        if (!existing) {
          existing = { name, children: [] };
          currentLevel.push(existing);
        }
        currentLevel = existing.children;
      }
    });
  });

  return tree;
}

const desiredStructure = buildTree(inputData);
console.log(JSON.stringify(desiredStructure, null, 2));

Explanation:

  • Data Processing: The function buildTree() traverses each path in the inputData array.
  • Node Construction: For each name in the path, it either finds an existing child node or creates a new one.
  • Value Assignment: Once it reaches the penultimate node, it assumes the next item is the numeric value for population or similar.

This code snippet will convert your flat array into the nested structure, aligning with your requirement and handling varying row lengths effectively. Modify the indexing logic if your data structure varies considerably. The recursive aspect here is achieved by calling buildTree and traversing the nested children structures. Adjust further based on any additional specifics of your input data.