Recursive string parsing into object - JavaScript

Recursive string parsing transforms an array of dot-separated strings into a nested JavaScript object structure. This technique is useful for converting flat configuration paths into hierarchical data structures.

Problem Description

Given an array of strings following the pattern x.y.x.y..., we need to create a nested object where the last segment becomes a value in an array, and preceding segments form the nested structure.

For example, if the input array is:

const arr = [
    "country.UK.level.1",
    "country.UK.level.2", 
    "country.US.level.1",
    "country.UK.level.3"
];

The expected output should be:

{
    "country": {
        "UK": {
            "level": ["1", "2", "3"]
        },
        "US": {
            "level": ["1"]
        }
    }
}

Solution

The solution uses a recursive approach to build the nested object structure by splitting each string and traversing the path:

const arr = [
    "country.UK.level.1",
    "country.UK.level.2",
    "country.US.level.1",
    "country.UK.level.3"
];

const stringToObject = arr => {
    const obj = {};
    
    arr.forEach(str => {
        let curr = obj;
        let splitted = str.split('.');
        let last = splitted.pop();
        let beforeLast = splitted.pop();
        
        splitted.forEach(sub => {
            if(!curr.hasOwnProperty(sub)){
                curr[sub] = {};
            }
            curr = curr[sub];
        });
        
        if(!curr[beforeLast]){
            curr[beforeLast] = [];
        }
        curr[beforeLast].push(last);
    });
    
    return obj;
};

console.log(JSON.stringify(stringToObject(arr), undefined, 4));
{
    "country": {
        "UK": {
            "level": [
                "1",
                "2", 
                "3"
            ]
        },
        "US": {
            "level": [
                "1"
            ]
        }
    }
}

How It Works

The algorithm processes each string in three steps:

  1. Split and Extract: Split the string by dots, then extract the last value and the second-to-last key
  2. Build Path: Traverse through the remaining path segments, creating nested objects as needed
  3. Store Value: Create an array for the second-to-last key if it doesn't exist, then push the last value

Key Features

  • Handles Unsorted Input: The order of strings in the input array doesn't matter
  • Dynamic Nesting: Supports strings of any length with deeper nesting levels
  • Array Grouping: Automatically groups final values into arrays under their parent keys
  • Duplicate Prevention: Uses hasOwnProperty() to avoid overwriting existing nested objects

Conclusion

This recursive string parsing approach efficiently converts flat dot-notation paths into nested object structures. It's particularly useful for configuration management, API responses, and data transformation tasks where hierarchical organization is needed.

Updated on: 2026-03-15T23:19:00+05:30

589 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements